import matplotlib.pyplot as plt
import numpy as np
= np.linspace(0, 10, 100)
t = np.sin(t)
y
='sin(t)', color='b')
plt.plot(t, y, label'Time (s)')
plt.xlabel('Amplitude')
plt.ylabel('Line plot')
plt.title(
plt.legend() plt.show()
2 Plot Types in Matplotlib
Matplotlib offers a variety of plot types suitable for different purposes. In this chapter, we introduce the most important plot types and explain their use cases.
2.1 1. Line plots (plt.plot()
)
Line plots are excellent for visualizing trends over time.
2.2 2. Scatter Plots (plt.scatter()
)
Scatter plots are used to show relationships between two variables.
= np.random.rand(50)
x = np.random.rand(50)
y
='r', alpha=0.5)
plt.scatter(x, y, color'Variable X')
plt.xlabel('Variable Y')
plt.ylabel('Scatter Plot')
plt.title( plt.show()
2.3 3. Bar plots (plt.bar()
)
Bar plots are suitable for representing categorical data.
= ['A', 'B', 'C', 'D']
categories = [3, 7, 1, 5]
values
='g')
plt.bar(categories, values, color'Categories')
plt.xlabel('Value')
plt.ylabel('Bar plot')
plt.title( plt.show()
2.4 4. Histograms (plt.hist()
)
Histograms show the distribution of numerical data.
= np.random.randn(1000)
data =30, color='purple', alpha=0.7)
plt.hist(data, bins'Value')
plt.xlabel('Frequency')
plt.ylabel('Histogram')
plt.title( plt.show()
2.5 5. Box Plots (plt.boxplot()
)
Box plots help visualize outliers and data distribution.
= [np.random.randn(100) for _ in range(4)]
data =['A', 'B', 'C', 'D'])
plt.boxplot(data, labels'Value')
plt.ylabel('Box Plot')
plt.title( plt.show()
/tmp/ipykernel_3862/3930898833.py:2: MatplotlibDeprecationWarning: The 'labels' parameter of boxplot() has been renamed 'tick_labels' since Matplotlib 3.9; support for the old name will be dropped in 3.11.
plt.boxplot(data, labels=['A', 'B', 'C', 'D'])
2.6 6. Heatmaps (plt.imshow()
)
Heatmaps are useful for displaying 2D data.
= np.random.rand(10, 10)
data ='coolwarm', interpolation='nearest')
plt.imshow(data, cmap
plt.colorbar()'Heatmap')
plt.title( plt.show()
2.7 Conclusion
The choice of plot type depends on the nature of the data and the intended representation. In the next chapter, we will explore customizing and adapting plots.