Matplotlib Tutorial
Introduction to Matplotlib:
Matplotlib is a powerful Python library used for creating visualizations and plots. It provides a wide range of
functions and methods to generate different types of plots, such as line plots, bar plots, scatter plots, histograms,
and more.
To use Matplotlib, you need to import the module:
import matplotlib.pyplot as plt
Line Plot:
Basic Line Plot:
Create a simple line plot.
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.show()
Customizing Line Plot:
Customize the line plot with labels, title, and grid.
plt.plot(x, y, label='Line 1')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')
plt.grid(True)
plt.legend()
plt.show()
Bar Plot:
Vertical Bar Plot:
Create a vertical bar plot.
x = ['A', 'B', 'C', 'D']
y = [10, 5, 7, 12]
plt.bar(x, y)
plt.show()
Horizontal Bar Plot:
Create a horizontal bar plot.
plt.barh(x, y)
plt.show()
Scatter Plot:
Basic Scatter Plot:
Create a scatter plot.
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.scatter(x, y)
plt.show()
Customizing Scatter Plot:
Customize the scatter plot with colors and markers.
plt.scatter(x, y, color='red', marker='x')
plt.show()
Histogram:
Basic Histogram:
Create a histogram.
data = [1, 1, 1, 2, 2, 3, 3, 4, 5]
plt.hist(data, bins=5)
plt.show()
Customizing Histogram:
Customize the histogram with labels and colors.
plt.hist(data, bins=5, edgecolor='black', alpha=0.7)
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()
Pie Chart:
Basic Pie Chart:
Create a basic pie chart.
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
plt.pie(sizes, labels=labels)
plt.show()
Customizing Pie Chart:
Customize the pie chart with colors and explode.
explode = [0, 0.1, 0, 0]
colors = ['red', 'blue', 'green', 'yellow']
plt.pie(sizes, labels=labels, explode=explode, colors=colors, shadow=True)
plt.show()
Exercise:
1. Create a line plot with x-axis values [1, 2, 3, 4] and y-axis values [1, 4, 9, 16].
2. Create a bar plot with x-axis labels ['A', 'B', 'C'] and y-axis values [10, 5, 7].
3. Create a scatter plot with x-axis values [1, 2, 3, 4, 5] and y-axis values [2, 4, 6, 8, 10].
4. Create a histogram with data [1, 1, 1, 2, 2, 3, 3, 4, 5] and 5 bins.
5. Create a pie chart with labels ['A', 'B', 'C', 'D'] and sizes [15, 30, 45, 10].
6. Create a line plot with x-axis values [1, 2, 3, 4] and y-axis values [1, 8, 27, 64]. Customize it with labels and
title.
7. Create a bar plot with x-axis labels ['A', 'B', 'C'] and y-axis values [10, 5, 7]. Customize it with colors and
edgecolor.
8. Create a scatter plot with x-axis values [1, 2, 3, 4, 5] and y-axis values [2, 4, 6, 8, 10]. Customize it with colors
and markers.
9. Create a histogram with data [1, 1, 1, 2, 2, 3, 3, 4, 5] and 10 bins. Customize it with colors and alpha value.
10. Create a pie chart with labels ['A', 'B', 'C', 'D'] and sizes [15, 30, 45, 10]. Customize it with explode and
shadow.