Detailed explanation of DataFrame.plot function (6)

Detailed explanation of DataFrame.plot function (6)

Use subplot() to make subplots, position each subplot, set data and graphics, and understand the meaning and function of fig and ax(axs).

1. subplot()

matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, width_ratios=None, height_ratios=None, subplot_kw=None, gridspec_kw=None, **fig_kw)

nrows=1, ncols=1, the number of row and row subgraphs, default 1

sharex=False, sharey=False, subplots share XY axes, not shared by default
1.True or 'all': x or y-axis attributes will be shared in all subplots.
2.False or 'none': every The x or y axes of the subplots are independent parts
3. 'row': Each subplot shares a row (row) on an x ​​or y axis
4. 'col': Each subplot shares a column (row) on an x ​​or y axis ( column)
When the subplot has a shared column on the x-axis ('col'), only the x tick mark of the bottom subplot is visible.
Similarly, when the subplot has a shared row ('row') on the y-axis, only the y tick mark of the first column of the subplot is visible.

squeeze: Boolean type, optional parameter, default: True.
If True, additional dimensions are squeezed out of the returned Axes object.
If only one subgraph is constructed (nrows=ncols=1), the result is a single Axes object returned as a scalar.
For N 1 or 1 N subgraphs, return a 1-dimensional array.
For N*M, N>1 and M>1 return a 2D array.
If False, no extrusion is performed: a 2D array of Axes instances is returned, even if it ends up being 1x1.

subplot_kw: dictionary type, optional parameter. Pass the dictionary keys to add_subplot() to create each subplot.

gridspec_kw dictionary type, optional parameter. Pass the dictionary keys to the GridSpec constructor to create a subgraph and place it in the grid.

**fig_kw: Pass all detailed keyword parameters to the figure() function

Return result:
fig: matplotlib.figure.Figure object
ax: Axes (axis) object or array of Axes (axis) objects.

2.Example

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame({'apple':abs(np.random.randn(8)),'orange':abs(np.random.randn(8)),
                   'grape':abs(np.random.randn(8)),'banana':abs(np.random.randn(8))},
                  index=pd.date_range('2022-01-01', periods=8))
# 2*2 个子图
fig, axs = plt.subplots(2, 2, sharex=True, sharey=True,figsize=(10,6))

# 主图的标题
fig.suptitle ('Subplots')

#第一个子图
axs[0, 0].scatter(df.index, df['apple'], s=80, color='r', marker=">")
axs[0, 0].set_title("scatter >")

#第二个子图
axs[0, 1].bar(df.index, df['orange'], color='y')
axs[0, 1].set_title("bar")

#第三个子图
axs[1, 0].plot(df.index, df['grape'], color='b',marker='H',markersize = 10,linestyle='-.',linewidth=2)
axs[1, 0].set_title("line ")

#第四个子图
axs[1, 1].scatter(df.index, df['banana'], s=100, color='g',marker='<')
axs[1, 1].set_title("scatter <")

plt.tight_layout()
plt.show()

The effect is as follows:
Insert image description here

3. Understand subplot() return value

subplot() return value:
fig: matplotlib.figure.Figure object
ax: Axes (axis) object or array of Axes (axis) objects.

print(type(fig))
print(type(plt.figure))
print(type(axs))

The result is as follows:

<class ‘matplotlib.figure.Figure’>
<class ‘function’>
<class ‘numpy.ndarray’>

  • plt.figure is a function <class 'function'>
  • plt.figure() returns an instance fig of class <class 'matplotlib.figure.Figure'>
  • The type of ax needs to be determined according to the parameters of plt.subplots(). plt.subplots() will return an instance ax of <class 'matplotlib.axes.Axes'>, and plt.subplots(2,2) will return an Axes instance. Collection of axs. ax/axs/axes generally refers to an instance or a collection of instances of class Axes.

4. Sub-picture deletion

import matplotlib.pyplot as plt
# 添加3行3列子图9个子图
fig, axes = plt.subplots(3, 3)
# 为第1个子图绘制图形
axes[0, 0].bar(range(1, 4), range(1, 4))
# 为第5个子图绘制图形
axes[1, 1].pie([4, 5, 6])
# 为第9个子图绘制图形
axes[2, 2].plot([1,2,3], 'o')
plt.show()

Insert image description here

import matplotlib.pyplot as plt
# 添加3行3列子图9个子图
fig, axes = plt.subplots(3, 3)
# 为第1个子图绘制图形
axes[0, 0].bar(range(1, 4), range(1, 4))
# 为第5个子图绘制图形
axes[1, 1].pie([4, 5, 6])
# 为第9个子图绘制图形
axes[2, 2].plot([1,2,3], 'o')
# 删除没有用到的子图
for i in range(3):
    for j in range(3):
        if i != j:
            axes[i, j].remove()
plt.show()

The results are as follows:
Insert image description here
Previous article scatter, box and df.boxplot function demonstration

Guess you like

Origin blog.csdn.net/qq_39065491/article/details/132554020