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.

import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(0, 10, 100)
y = np.sin(t)

plt.plot(t, y, label='sin(t)', color='b')
plt.xlabel('Time (s)', fontsize=12)
plt.ylabel('Amplitude', fontsize=12)
plt.title('Line Plot with Labels', fontsize=14)
plt.legend()
plt.show()

3.2 2. Adjusting Axes

The scaling of the axes should be chosen appropriately to best represent the data.

plt.plot(t, y, label='sin(t)', color='b')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.xlim(0, 10)
plt.ylim(-1.2, 1.2)
plt.grid(True, linestyle='--', alpha=0.7)
plt.title('Line Plot with Adjusted Axes')
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
plt.plot(t, np.sin(t), linestyle='-', color='r', label='sin(t)')
plt.plot(t, np.cos(t), linestyle='--', color='g', label='cos(t)')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title('Customization of Colors and Line Styles')
plt.legend()
plt.show()

3.4 4. Multiple Plots with Subplots

Sometimes it’s useful to display multiple plots in a single figure.

fig, axs = plt.subplots(2, 1, figsize=(6, 6))
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')
plt.tight_layout()
plt.show()

3.5 5. Saving Plots

Plots can be saved in various formats.

plt.plot(t, y, label='sin(t)', color='b')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title('Saving a Plot')
plt.legend()
plt.savefig('my_plot.png', dpi=300)
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.