[PYTHON] Draw multiple graphs using matplotlib figures and axes

Overview

If you use matplotlib ad hoc without reading the documentation, I'm not sure I'm curious about the figures and axes that remain unclear (I don't know)

Why i wrote this

After reading the document for a moment, I felt like I knew it, so I wanted other people to understand it.

To understand properly

-Read Official -Match summary of matplotlib -Maybe you will be happy to know the hierarchical structure of matplotlib

Contents

Premise

The following is omitted.

import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt

First of all

This is the relationship between figure and axes. figure is the entire drawing area, axes is the drawing area of the graph

--When the graph has one drawing area pic1.png

--When the graph has two drawing areas (1 row and 2 columns) pic2.png

Let's make two drawing areas of empty graph with 1 row and 2 columns arrangement

#Size 8,Create a drawing area of 4 and a drawing area of a 1-by-2 graph
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8,4))

#Set the title of the figure
fig.suptitle("figure_title")

#Set a title in the first drawing area
ax[0].set_title("axes0_title")

#Set a title in the second drawing area
ax[1].set_title("axes1_title")

Execution result スクリーンショット 2020-11-01 21.15.23.png

Try drawing a graph

#Make 10000 numbers
norm_arr = np.random.randn(10000)

#Size 6,Create a drawing area of 3 and a drawing area of a 1-by-2 graph
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(6,3))

#Set the title of the figure
fig.suptitle("figure_title")

#Set a title for the first axes
ax[0].set_title("axes0")

#Draw a graph on the first axes
ax[0].hist(norm_arr)

#Set a title for the second axes
ax[1].set_title("axes1")

#Draw a graph with seaborn on the second axes
sns.histplot(norm_arr, ax=ax[1])

Execution result スクリーンショット 2020-11-01 21.21.37.png

Try drawing on top of each other

#Add the following code to the end of the code in the previous section
x_scat = np.random.randn(100)
y_scat = np.random.randint(low=100, high=500, size=(1,100))
ax[1].scatter(x_scat, y_scat) #Write a scatter plot on the first axes

Execution result Execution result You can see that it is drawn over the second axes. スクリーンショット 2020-11-01 21.59.04.png

end

Recommended Posts

Draw multiple graphs using matplotlib figures and axes
Draw multiple graphs using Pandas
[Python] How to draw multiple graphs with Matplotlib
Animate multiple graphs with matplotlib
Easy to draw graphs with matplotlib
Japanese settings for matplotlib and Seaborn axes
How to title multiple figures with matplotlib
How to draw a graph using Matplotlib
Matplotlib Basics / Differences between fig and axes
Create interactive 3D graphs on JupyterLab using matplotlib
Try using matplotlib
Draw an Earth-like flow animation with matplotlib and cartopy
Adjust the ratio of multiple figures with the matplotlib gridspec