4  Advanced Techniques in Matplotlib

In this chapter, we explore some advanced features of Matplotlib that are especially useful for scientific data visualization.

4.1 1. Logarithmic Scales

Logarithmic scales are often used when values span several orders of magnitude.

import matplotlib.pyplot as plt
import numpy as np

x = np.logspace(0.1, 2, 100)
y = np.log10(x)

plt.plot(x, y, label='log10(x)', color='b')
plt.xscale('log')
plt.xlabel('X Value (log scale)')
plt.ylabel('Y Value')
plt.title('Logarithmic Scaling')
plt.legend()
plt.grid(True, which='both', linestyle='--', alpha=0.7)
plt.show()

4.2 2. Twin Axes for Different Scales

Sometimes you may want to display two different y-axes in one plot.

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.exp(x / 3)

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-', label='sin(x)')
ax2.plot(x, y2, 'b--', label='exp(x/3)')

ax1.set_xlabel('X Value')
ax1.set_ylabel('Sine', color='g')
ax2.set_ylabel('Exponential', color='b')
ax1.set_title('Twin Axes for Different Scales')
plt.show()

4.3 3. Annotations in Plots

Important points or values in a plot can be highlighted using annotations.

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

plt.plot(x, y, label='sin(x)')
plt.xlabel('X Value')
plt.ylabel('Amplitude')
plt.title('Annotations in Matplotlib')
plt.annotate('Maximum Value', xy=(np.pi/2, 1), xytext=(2, 1.2),
             arrowprops=dict(facecolor='red', shrink=0.05))
plt.legend()
plt.show()

4.4 Conclusion

These advanced features help make scientific plots more informative. In the next chapter, we will look at best practices and common mistakes in scientific visualization.