import matplotlib.pyplot as plt
import numpy as np
= np.logspace(0.1, 2, 100)
x = np.log10(x)
y
='log10(x)', color='b')
plt.plot(x, y, label'log')
plt.xscale('X Value (log scale)')
plt.xlabel('Y Value')
plt.ylabel('Logarithmic Scaling')
plt.title(
plt.legend()True, which='both', linestyle='--', alpha=0.7)
plt.grid( plt.show()
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.
4.2 2. Twin Axes for Different Scales
Sometimes you may want to display two different y-axes in one plot.
= np.linspace(0, 10, 100)
x = np.sin(x)
y1 = np.exp(x / 3)
y2
= plt.subplots()
fig, ax1 = ax1.twinx()
ax2 'g-', label='sin(x)')
ax1.plot(x, y1, 'b--', label='exp(x/3)')
ax2.plot(x, y2,
'X Value')
ax1.set_xlabel('Sine', color='g')
ax1.set_ylabel('Exponential', color='b')
ax2.set_ylabel('Twin Axes for Different Scales')
ax1.set_title( plt.show()
4.3 3. Annotations in Plots
Important points or values in a plot can be highlighted using annotations.
= np.linspace(0, 10, 100)
x = np.sin(x)
y
='sin(x)')
plt.plot(x, y, label'X Value')
plt.xlabel('Amplitude')
plt.ylabel('Annotations in Matplotlib')
plt.title('Maximum Value', xy=(np.pi/2, 1), xytext=(2, 1.2),
plt.annotate(=dict(facecolor='red', shrink=0.05))
arrowprops
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.