Matplotlib is a powerful plotting library in Python that allows you to create a wide range of visualizations. When working with complex datasets or multiple related plots, it's often necessary to use subplots or multiple figures. In this guide, we'll explore how to effectively use these features to create compelling and informative visualizations.
Subplots are a way to create multiple plots within a single figure. They're incredibly useful when you want to compare different datasets or show various aspects of the same data side by side.
Let's start with a basic example:
import matplotlib.pyplot as plt import numpy as np # Create some sample data x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) # Create a figure with two subplots fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4)) # Plot data on the first subplot ax1.plot(x, y1) ax1.set_title('Sine Wave') # Plot data on the second subplot ax2.plot(x, y2) ax2.set_title('Cosine Wave') # Add a main title to the figure fig.suptitle('Trigonometric Functions', fontsize=16) plt.tight_layout() plt.show()
In this example, we create a figure with two subplots side by side. The plt.subplots(1, 2)
function creates a figure with one row and two columns of subplots.
Matplotlib offers great flexibility in arranging subplots. You can create grids of any size and even have subplots span multiple rows or columns.
Here's an example of a more complex layout:
fig = plt.figure(figsize=(12, 8)) # Create a 2x2 grid of subplots ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3) ax4 = fig.add_subplot(2, 2, 4) # Plot some data ax1.plot(np.random.rand(50)) ax2.scatter(np.arange(50), np.random.rand(50)) ax3.bar(np.arange(10), np.random.rand(10)) ax4.hist(np.random.randn(1000), bins=30) # Customize titles ax1.set_title('Line Plot') ax2.set_title('Scatter Plot') ax3.set_title('Bar Plot') ax4.set_title('Histogram') plt.tight_layout() plt.show()
This script creates a 2x2 grid of subplots, each with a different type of plot.
Sometimes, you might want to create separate figures instead of subplots within a single figure. This is useful when you want to generate multiple independent visualizations.
Here's how you can work with multiple figures:
# Create the first figure plt.figure(1, figsize=(6, 4)) plt.plot(np.random.rand(100)) plt.title('Figure 1: Random Data') # Create the second figure plt.figure(2, figsize=(6, 4)) plt.scatter(np.arange(50), np.random.rand(50)) plt.title('Figure 2: Scatter Plot') # Show both figures plt.show()
This script creates two separate figures, each with its own plot.
When working with related data, it's often useful to share axes between subplots:
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(8, 6)) x = np.linspace(0, 10, 100) ax1.plot(x, np.sin(x)) ax2.plot(x, np.cos(x)) ax1.set_title('Sine and Cosine Waves') ax2.set_xlabel('X-axis') plt.tight_layout() plt.show()
This example creates two subplots that share the same x-axis, making it easier to compare the two plots.
For even more control over your subplot layouts, you can use GridSpec:
from matplotlib.gridspec import GridSpec fig = plt.figure(figsize=(12, 8)) gs = GridSpec(3, 3, figure=fig) ax1 = fig.add_subplot(gs[0, :]) ax2 = fig.add_subplot(gs[1, :-1]) ax3 = fig.add_subplot(gs[1:, -1]) ax4 = fig.add_subplot(gs[-1, 0]) ax5 = fig.add_subplot(gs[-1, -2]) # Add plots to each subplot ax1.plot(np.random.rand(100)) ax2.scatter(np.arange(50), np.random.rand(50)) ax3.hist(np.random.randn(200), bins=20) ax4.bar(np.arange(10), np.random.rand(10)) ax5.imshow(np.random.rand(10, 10), cmap='viridis') plt.tight_layout() plt.show()
This creates a complex layout with subplots of different sizes and positions.
Subplots and multiple figures are powerful tools in Matplotlib that allow you to create rich, informative visualizations. By mastering these techniques, you can effectively communicate complex data and relationships in your plots. Remember to experiment with different layouts and configurations to find the best way to present your data.
08/12/2024 | Python
05/10/2024 | Python
06/12/2024 | Python
21/09/2024 | Python
26/10/2024 | Python
15/11/2024 | Python
06/10/2024 | Python
26/10/2024 | Python
14/11/2024 | Python
26/10/2024 | Python
05/10/2024 | Python