How to Create Subplots In Matplotlib?

12 minutes read

To create subplots in Matplotlib, you can use the plt.subplots() function. This function returns a figure object and an array of axes objects, which can be used to create multiple plots within the same figure.


Subplots allow you to organize multiple plots in a grid-like structure. Each plot can have its own individual properties and can be customized independently.


Here's an example of how you can create subplots in Matplotlib:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import matplotlib.pyplot as plt

# Create a figure and an array of axes objects
fig, axes = plt.subplots(nrows=2, ncols=2)

# Use the axes objects to plot on each subplot
axes[0, 0].plot(x1, y1)
axes[0, 0].set_title('Plot 1')

axes[0, 1].scatter(x2, y2)
axes[0, 1].set_title('Plot 2')

axes[1, 0].bar(x3, y3)
axes[1, 0].set_title('Plot 3')

axes[1, 1].hist(x4)
axes[1, 1].set_title('Plot 4')

plt.tight_layout()
plt.show()


In this example, nrows=2 and ncols=2 create a grid with 2 rows and 2 columns, resulting in four subplots. Each subplot is accessed using indexing, such as axes[0, 0] to access the first subplot in the first row, and axes[1, 1] to access the second subplot in the second row.


You can then use the axes objects to plot your data on each subplot, set titles, apply customizations, and so on. Finally, plt.tight_layout() ensures that the subplots are properly spaced, and plt.show() displays the figure with all the subplots.


Using subplots in Matplotlib allows for effective comparisons and visualizations of multiple plots within a single figure.

Best Matplotlib Books to Read in 2024

1
Data Visualization in Python with Pandas and Matplotlib

Rating is 5 out of 5

Data Visualization in Python with Pandas and Matplotlib

2
Matplotlib 3.0 Cookbook: Over 150 recipes to create highly detailed interactive visualizations using Python

Rating is 4.9 out of 5

Matplotlib 3.0 Cookbook: Over 150 recipes to create highly detailed interactive visualizations using Python

3
Matplotlib for Python Developers

Rating is 4.8 out of 5

Matplotlib for Python Developers

4
Numerical Python: Scientific Computing and Data Science Applications with Numpy, SciPy and Matplotlib

Rating is 4.7 out of 5

Numerical Python: Scientific Computing and Data Science Applications with Numpy, SciPy and Matplotlib

5
Matplotlib 2.x By Example: Multi-dimensional charts, graphs, and plots in Python

Rating is 4.6 out of 5

Matplotlib 2.x By Example: Multi-dimensional charts, graphs, and plots in Python

6
Matplotlib for Python Developers: Effective techniques for data visualization with Python, 2nd Edition

Rating is 4.5 out of 5

Matplotlib for Python Developers: Effective techniques for data visualization with Python, 2nd Edition

7
Python Data Analytics: With Pandas, NumPy, and Matplotlib

Rating is 4.4 out of 5

Python Data Analytics: With Pandas, NumPy, and Matplotlib

8
Python and Matplotlib Essentials for Scientists and Engineers (Iop Concise Physics)

Rating is 4.3 out of 5

Python and Matplotlib Essentials for Scientists and Engineers (Iop Concise Physics)

9
Hands-On Data Analysis with Pandas: A Python data science handbook for data collection, wrangling, analysis, and visualization, 2nd Edition

Rating is 4.2 out of 5

Hands-On Data Analysis with Pandas: A Python data science handbook for data collection, wrangling, analysis, and visualization, 2nd Edition

10
Data Visualization with Python for Beginners: Visualize Your Data using Pandas, Matplotlib and Seaborn (Machine Learning & Data Science for Beginners)

Rating is 4.1 out of 5

Data Visualization with Python for Beginners: Visualize Your Data using Pandas, Matplotlib and Seaborn (Machine Learning & Data Science for Beginners)


What is the significance of legends in subplots?

Legends in subplots serve several important purposes in storytelling:

  1. Deepening the narrative: Legends provide additional layers of history, culture, and mythology to the story. They can enhance the world-building by adding richness and depth, creating a sense of believability and authenticity.
  2. Foreshadowing: Legends can act as subtle hints or foreshadowing elements for the main plot or character arcs. They often contain symbolic or thematic elements that mirror or hint at future events, helping the audience anticipate or interpret upcoming developments.
  3. Moral lessons and thematic exploration: Legends often convey moral or ethical messages, exploring broader themes and ideas through allegory. By incorporating these stories into subplots, authors can explore complex themes in a nuanced way, allowing readers to engage with these ideas on multiple levels.
  4. Character development: Legends can be used to shape and develop characters in subplots. The way characters respond to or interpret legends can reveal their values, fears, aspirations, or worldview. Legends can also serve as catalysts for character growth or change, as characters may be inspired, challenged, or forced to confront their beliefs through encounters with legendary stories.
  5. Parallel storylines: Legends in subplots can create parallel storylines that run alongside the main plot. These parallel narratives can add depth and complexity to the overall story by exploring different perspectives or experiences related to the central themes.
  6. Subtext and hidden meanings: Legends often have underlying meanings that invite interpretation and analysis. Through subplots involving legends, authors can weave subtext and hidden meanings into the story, allowing for deeper exploration and providing opportunities for readers to engage intellectually with the material.


Overall, legends in subplots add texture, symbolism, and thematic relevance to stories, enriching the narrative and enhancing the reader's experience. They help build a more immersive and engaging world while providing opportunities for exploration and interpretation.


What is the purpose of gridlines in data visualization?

Gridlines in data visualization serve as visual aids that help users interpret and understand the data more effectively. The main purposes of gridlines are:

  1. Reference and comparison: Gridlines provide a frame of reference by displaying a consistent scale across the visual. This allows users to compare and gauge the values of data points more accurately.
  2. Alignment and organization: Gridlines create a structured and organized layout for the data. They help align elements within the visualization, making it easier to read and interpret.
  3. Data precision: Gridlines assist in determining the exact values of data points by providing a set of horizontal and vertical lines that intersect at specific intervals. This aids in the precise analysis of the data.
  4. Trend identification: Gridlines support the identification of trends and patterns by providing clear horizontal and vertical guidelines. Users can spot correlations and trends by observing how data points align with the gridlines.
  5. Communication: Gridlines help in effectively communicating the data to others. They provide clarity and context, allowing viewers to understand the information being presented.


Overall, gridlines enhance the readability, accuracy, and interpretation of data visualizations by providing a consistent reference framework.


How to set the figure size in Matplotlib?

To set the figure size in Matplotlib, you can use the figure function and specify the figsize parameter.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import matplotlib.pyplot as plt

# Set the figure size to 8 inches in width and 6 inches in height
plt.figure(figsize=(8, 6))

# Plot your data
plt.plot(x, y)

# Show the plot
plt.show()


In the example above, plt.figure(figsize=(8, 6)) sets the figure size to 8 inches in width and 6 inches in height. You can adjust the values of figsize to your desired dimensions.


What is the default font size in Matplotlib?

The default font size in Matplotlib is 10 points.


How to modify the font size in subplot labels and titles?

To modify the font size in subplot labels and titles, you can use the set_xlabel(), set_ylabel(), and set_title() methods of the Axes object.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import matplotlib.pyplot as plt

# Create subplot
fig, ax = plt.subplots()

# Plot some data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
ax.plot(x, y)

# Modify the font size of the x label
ax.set_xlabel('X Label', fontsize=14)

# Modify the font size of the y label
ax.set_ylabel('Y Label', fontsize=14)

# Modify the font size of the title
ax.set_title('Plot Title', fontsize=16)

# Show the plot
plt.show()


In this example, the set_xlabel(), set_ylabel(), and set_title() methods are used with the fontsize parameter to set the font size of the labels and title. You can modify the fontsize parameter to adjust the font size to your liking.


What is the file format for saving subplots in Matplotlib?

The file format for saving subplots in Matplotlib can be specified by providing a file extension in the savefig() function. Some commonly used file formats include:

  • PNG (Portable Network Graphics) - .png
  • JPEG (Joint Photographic Experts Group) - .jpg or .jpeg
  • PDF (Portable Document Format) - .pdf
  • SVG (Scalable Vector Graphics) - .svg
  • EPS (Encapsulated PostScript) - .eps
Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To plot more than one image with Matplotlib, you can use multiple subplots or axes within a single figure. Here's how you can achieve this:Import the required libraries: import matplotlib.pyplot as plt Create a figure object and define the number of rows a...
To animate text in Matplotlib, you can follow these steps:Import the necessary libraries: Begin by importing the required libraries, including Matplotlib and FuncAnimation from the animation module. import matplotlib.pyplot as plt from matplotlib.animation imp...
To add two or more images using matplotlib, you can use the imshow() function multiple times in the same figure. First, you need to import the necessary libraries, such as matplotlib and numpy. Then, create a figure and add subplots using the subplots() functi...