In addition to basic plotting, Matplotlib offers advanced techniques that allow for more complex visualizations. One such technique is the use of subplots, which allows multiple plots to be displayed within a single figure. Subplots can be created using the plt.subplots
function, specifying the number of rows and columns as parameters. For example:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2)
ax1 = axes[0, 0]
ax2 = axes[0, 1]
ax3 = axes[1, 0]
ax4 = axes[1, 1]
ax1.plot(x, y1)
ax2.scatter(x, y2)
ax3.bar(x, y3)
ax4.hist(x, bins=10)
plt.show()
This code creates a 2x2 grid of subplots and plots different types of visualizations on each subplot.
Another useful technique is the inclusion of multiple axes within a single figure using the plt.twinx
function. This allows for the overlaying of multiple plots on top of each other, each with its own y-axis. For example:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'r-')
ax2.plot(x, y2, 'b-')
plt.show()
This code creates two plots with different y-axis scales, allowing for the visualization of multiple datasets on a single figure.