Understanding the components of subplots in Matplotlib is key to creating complex and well-organized plots. Let's break down the main components involved when working with subplots step by step.
plt.figure()
to start a new figure. Parameters like figsize
can set the figure dimensions.fig.add_subplot()
, plt.subplots()
, or plt.axes()
.plt.subplots(nrows, ncols)
to create a figure and a grid of subplots. This function returns a figure object and an array of axes objects.set_xticks()
, set_xticklabels()
, and set_xlabel()
for the x-axis, with analogous methods for the y-axis.ax.set_xticks()
, ax.set_xticklabels()
, and similar methods for the y-axis. The appearance can be finely tuned with ax.tick_params()
.ax.grid()
to add a grid to an axes object. It's customizable with parameters for line style, width, and color.ax.legend()
. The legend automatically associates labels with the plot elements.ax.set_title()
and label the axes with ax.set_xlabel()
and ax.set_ylabel()
.plt.tight_layout()
to automatically adjust the spacing between subplots to prevent overlap. plt.subplots_adjust()
offers more control over spacing.Creating a plot with multiple subplots typically follows this workflow:
Understanding and utilizing these components allows for the creation of complex, informative, and visually appealing plots in Matplotlib.
Let's integrate all the discussed components of Matplotlib subplots into a comprehensive example. We'll create a figure with multiple subplots, demonstrating various types of data visualizations and customizations. This example will simulate data for a fictional scenario involving temperature and ice cream sales data over twelve months.
First, let's define our synthetic dataset:
import numpy as np
# Seed for reproducibility
np.random.seed(0)
# Months of the year
months = np.arange(1, 13)
# Average temperature (in degrees Celsius)
temperature = np.random.uniform(low=10, high=30, size=12)
# Ice cream sales (in thousands)
sales = temperature * 50 + np.random.normal(loc=0, scale=100, size=12)
Next, we create a figure with a 2x2 grid of subplots:
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2, figsize=(12, 10))
# Flatten the array for easy direct indexing
axs = axs.flatten()
Now, we'll plot different types of plots in each subplot:
axs[0].plot(months, temperature, marker='o', linestyle='-', color='blue')
axs[0].set_title('Monthly Average Temperature')
axs[0].set_xlabel('Month')
axs[0].set_ylabel('Temperature (°C)')
axs[0].grid(True)
axs[1].scatter(temperature, sales, color='red')
axs[1].set_title('Ice Cream Sales vs. Temperature')
axs[1].set_xlabel('Temperature (°C)')
axs[1].set_ylabel('Sales (thousands)')
axs[1].grid(True)
axs[2].bar(months, sales, color='green')
axs[2].set_title('Monthly Ice Cream Sales')
axs[2].set_xlabel('Month')
axs[2].set_ylabel('Sales (thousands)')
Let's add an overall title and handle the unused subplot:
# Overall figure title
fig.suptitle('Yearly Weather and Ice Cream Sales Analysis', fontsize=16)
# Hide the 4th subplot (unused)
axs[3].axis('off')
# Adjust layout to prevent overlap
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
# Display the plot
plt.show()
In this example, we've covered the following concepts:
plt.tight_layout()
to adjust the spacing between subplots for a cleaner presentation.This comprehensive example demonstrates how to use Matplotlib's subplot capabilities to create multi-faceted visualizations, combining various data plots within a single figure for effective data analysis and presentation.
import numpy as np
# Seed for reproducibility
np.random.seed(0)
# Months of the year
months = np.arange(1, 13)
# Average temperature (in degrees Celsius)
temperature = np.random.uniform(low=10, high=30, size=12)
# Ice cream sales (in thousands)
sales = temperature * 50 + np.random.normal(loc=0, scale=100, size=12)
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2, figsize=(12, 10))
# Flatten the array for easy direct indexing
axs = axs.flatten()
axs[0].plot(months, temperature, marker='o', linestyle='-', color='blue')
axs[0].set_title('Monthly Average Temperature')
axs[0].set_xlabel('Month')
axs[0].set_ylabel('Temperature (°C)')
axs[0].grid(True)
axs[1].scatter(temperature, sales, color='red')
axs[1].set_title('Ice Cream Sales vs. Temperature')
axs[1].set_xlabel('Temperature (°C)')
axs[1].set_ylabel('Sales (thousands)')
axs[1].grid(True)
axs[2].bar(months, sales, color='green')
axs[2].set_title('Monthly Ice Cream Sales')
axs[2].set_xlabel('Month')
axs[2].set_ylabel('Sales (thousands)')
# Overall figure title
fig.suptitle('Yearly Weather and Ice Cream Sales Analysis', fontsize=16)
# Hide the 4th subplot (unused)
axs[3].axis('off')
# Adjust layout to prevent overlap
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
# Display the plot
plt.show()
axs
fig
Creating 3D plots in Matplotlib is an effective way to visualize three-dimensional data. To do this, you'll use the mplot3d
toolkit, which extends Matplotlib's capabilities into three dimensions. In this example, we'll create a 3D scatter plot, which is useful for exploring the relationships between three variables.
First, make sure you have the necessary imports:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
For this example, let's create some synthetic data that represents measurements in three dimensions:
# Seed for reproducibility
np.random.seed(0)
# Generating synthetic data
x = np.random.standard_normal(100)
y = np.random.standard_normal(100)
z = np.random.standard_normal(100)
Now, let's set up the figure and axes for a 3D plot and add the data as a scatter plot:
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
# Scatter plot
scatter = ax.scatter(x, y, z, c=z, cmap='viridis', marker='o')
# Customizations
ax.set_title('3D Scatter Plot Example')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
# Color bar to show the scale of 'z' values
cbar = fig.colorbar(scatter, shrink=0.5, aspect=5)
cbar.set_label('Z value scale')
plt.show()
plt.figure()
initializes a new figure for plotting.fig.add_subplot(111, projection='3d')
adds a subplot to the figure with 3D projection, enabling 3D plotting.ax.scatter()
plots three-dimensional data. The c
parameter colors each point based on its z-value, and cmap='viridis'
applies a colormap.set_xlabel()
, set_ylabel()
, and set_zlabel()
methods. A title is also added to the plot.fig.colorbar()
adds a color bar to the side of the plot, indicating the scale of z-values, with its label set by cbar.set_label()
.3D plots like this are powerful tools for visualizing the relationships and structures in datasets that have more than two dimensions. By rotating the plot (which you can do interactively in many environments), you can get a better understanding of the spatial relationships between data points.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
# Seed for reproducibility
np.random.seed(0)
# Generating synthetic data
x = np.random.standard_normal(100)
y = np.random.standard_normal(100)
z = np.random.standard_normal(100)
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
# Scatter plot
scatter = ax.scatter(x, y, z, c=z, cmap='viridis', marker='o')
# Customizations
ax.set_title('3D Scatter Plot Example')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
# Color bar to show the scale of 'z' values
cbar = fig.colorbar(scatter, shrink=0.5, aspect=5)
cbar.set_label('Z value scale')
plt.show()
# Python Program to find the area of triangle
a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)