matplotlib
  1. matplotlib-figures-and-axes

Figures and Axes - ( Matplotlib Subplots and Figures )

Heading h2

Syntax

import matplotlib.pyplot as plt

fig, ax = plt.subplots(nrows, ncols)

Example

import matplotlib.pyplot as plt

fig, ax = plt.subplots(nrows=2, ncols=2)

ax[0][0].set_title('Plot 1')
ax[0][0].plot([1,2,3,4], [1,4,2,3])

ax[0][1].set_title('Plot 2')
ax[0][1].scatter([1,2,3,4], [1,4,2,3])

ax[1][0].set_title('Plot 3')
ax[1][0].plot([1,2,3,4], [4,2,3,1])

ax[1][1].set_title('Plot 4')
ax[1][1].scatter([1,2,3,4], [4,2,3,1])

Output

The output is a figure with four subplots, each with a different plot title.

Explanation

Matplotlib is a popular data visualization library in Python. Figures and axes are important concepts in Matplotlib as they allow us to create multiple plots in a single figure.

A figure is a window or page that contains all the subplots. An axes is a single plot within the figure.

In the above example, we create a 2x2 grid of subplots using the plt.subplots() method. This method returns a tuple of fig (the figure) and ax (the axes). We then use the set_title() method to set the subplot title, and then plot the respective data using the plot() and scatter() methods.

Use

Creating figures and axes allows us to create multiple plots in a single figure, thereby making it easier to compare and visualize multiple data sets. This is an essential step in data visualization and data analysis.

Important Points

  • A figure is a window or page that contains all the subplots
  • An axes is a single plot within the figure
  • plt.subplots() is used to create multiple subplots in a single figure
  • The method returns a tuple of fig (the figure) and ax (the axes)
  • set_title() is used to set the subplot title

Summary

In conclusion, figures and axes are important concepts in Matplotlib that allow us to create multiple plots in a single figure. The plt.subplots() method is used to create subplots within the figure, and set_title() is used to set the title of each subplot. This allows us to create more informative and effective data visualizations.

Published on: