5  Best Practices in Matplotlib: Common Mistakes and Improvements

In this chapter, we demonstrate a poor and an improved example for each common issue encountered when plotting with Matplotlib.

5.1 1. Missing Labels

5.1.1 ❌ Bad Example

import matplotlib.pyplot as plt
import numpy as np

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

plt.plot(x, y)
plt.show()

5.1.2 ✅ Improved Example

plt.plot(x, y, label='sin(x)', color='b')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title('Sine Curve')
plt.legend()
plt.show()

5.2 2. Poor Color Choice

5.2.1 ❌ Bad Example

plt.plot(x, y, color='yellow')
plt.show()

5.2.2 ✅ Improved Example

plt.plot(x, y, color='darkblue')
plt.grid(True, linestyle='--', alpha=0.7)
plt.title('Good Contrast for Better Readability')
plt.show()

5.3 3. Unreasonable Axis Scaling

5.3.1 ❌ Bad Example

plt.plot(x, y)
plt.ylim(0.5, 1)
plt.show()

5.3.2 ✅ Improved Example

plt.plot(x, y)
plt.ylim(-1.2, 1.2)
plt.xlim(0, 10)
plt.grid(True)
plt.title('Reasonable Axis Scaling')
plt.show()

5.4 4. Overcrowded with Too Many Lines

5.4.1 ❌ Bad Example

for i in range(10):
    plt.plot(x, np.sin(x + i * 0.2))
plt.show()

5.4.2 ✅ Improved Example

plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.legend()
plt.title('Less is More: Reduced Information Density')
plt.grid(True)
plt.show()

5.5 Conclusion

Good plots are characterized by clear labels, good readability, and a reasonable amount of information.