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)', fontsize=12)
plt.xlabel('Amplitude', fontsize=12)
plt.ylabel('Line Plot with Labels', fontsize=14)
plt.title(
plt.legend() plt.show()
3 Customization and Adapting of Plots in Matplotlib
A well-designed plot improves the readability and comprehension of the data presented. In this chapter, we will explore various ways to customize and adapt plots using Matplotlib.
3.1 1. Axis Labels and Plot Title
Clear axis and plot titles are essential for understanding a plot.
3.2 2. Adjusting Axes
The scaling of the axes should be chosen appropriately to best represent the data.
='sin(t)', color='b')
plt.plot(t, y, label'Time (s)')
plt.xlabel('Amplitude')
plt.ylabel(0, 10)
plt.xlim(-1.2, 1.2)
plt.ylim(True, linestyle='--', alpha=0.7)
plt.grid('Line Plot with Adjusted Axes')
plt.title(
plt.legend() plt.show()
3.3 3. Colors and Line Styles
Colors and line styles help to highlight important information in the plot.
3.3.1 Common Colors (Default Colors in Matplotlib)
Color | Code | Description |
---|---|---|
Blue | ‘b’ | blue |
Green | ‘g’ | green |
Red | ‘r’ | red |
Cyan | ‘c’ | cyan |
Magenta | ‘m’ | magenta |
Yellow | ‘y’ | yellow |
Black | ‘k’ | black |
White | ‘w’ | white |
3.3.2 Common Line Styles
Line Style | Code | Description |
---|---|---|
Solid | ‘-’ | default line |
Dashed | ‘–’ | long dashes |
Dotted | ‘:’ | only dots |
Dash-dot | ‘-.’ | alternating dash-dot |
='-', color='r', label='sin(t)')
plt.plot(t, np.sin(t), linestyle='--', color='g', label='cos(t)')
plt.plot(t, np.cos(t), linestyle'Time (s)')
plt.xlabel('Amplitude')
plt.ylabel('Customization of Colors and Line Styles')
plt.title(
plt.legend() plt.show()
3.4 4. Multiple Plots with Subplots
Sometimes it’s useful to display multiple plots in a single figure.
= plt.subplots(2, 1, figsize=(6, 6))
fig, axs 0].plot(t, np.sin(t), color='b')
axs[0].set_title('Sine Function')
axs[1].plot(t, np.cos(t), color='r')
axs[1].set_title('Cosine Function')
axs[
plt.tight_layout() plt.show()
3.5 5. Saving Plots
Plots can be saved in various formats.
='sin(t)', color='b')
plt.plot(t, y, label'Time (s)')
plt.xlabel('Amplitude')
plt.ylabel('Saving a Plot')
plt.title(
plt.legend()'my_plot.png', dpi=300)
plt.savefig( plt.show()
3.6 Conclusion
With careful customization, scientific plots can be significantly improved. In the next chapter, we will explore advanced techniques such as logarithmic scales and annotations.