为什么许多人都在matplotlib/pyplot/python里边使用fig, ax = plt.subplots()?

为什么许多人都在matplotlib/pyplot/python里边使用fig, ax = plt.subplots()?

fig, ax = plt.subplots()

在《Python for Data Analysis》 2nd Edition里边总是看到作者使用该函数,

虽然知道 它 等价于

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

但是,fig, ax = plt.subplots() 括号里的参数是什么意思呢?我该怎么用呢?比如 fig, ax = plt.subplots(2,1) 变为fig, ax = plt.subplots(2,2) 怎么配合图表函数使用呢?

一、fig, ax = plt.subplots()是做什么用的?

它是matplotlib输出的“总桌面/总画布”(fig:是figure的缩写),可以在其基础上添加 N行*M列的子画布。举个栗子:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
# 等价于
# fig = plt.figure()
# ax = plt.subplot(111)

fig, ax = plt.subplots(3,2)

plt.show()

输出为:

二、怎么设定参数,输出M*N个子图呢?

fig = plt.subplots()完整版代码为

fig = plt.subplots(nrows=整数M, ncols=整数N)

括号:两个参数设定 有M*N个子图。现在用代码验证:

2.1 这就需要进一步理解fig = plt.subplots()括号 里的参数。举个栗子:

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

fig, axes = plt.subplots(2, 1)

data = pd.Series(np.random.rand(16), index=list('abcdefghijklmnop'))
data.plot.bar(ax=axes[1], color='b', alpha = 0.5)
data.plot.barh(ax=axes[0], color='k', alpha=0.5)


plt.show()

# fig, axes = plt.subplots(2, 1):表示“(总)桌面”有2*1(即2行1列)个子图

ax=axes[1]:表示纵向bar图在(2,1)坐标位置,即下边的子图(python中起始数为0,代指第“1”个对象。所以此处“1”代表第“2”行,下同)

ax=axes[0]:表示横向barh图在(1,1)坐标位置,即上边的子图

2.2 在“(总)桌面上”怎么添加列维度 (比如 M*N+3)?

因为在上边代码的基础上改动fig, axes = plt.subplots为

fig, axes = plt.subplots(2, 2)

则会报错。怎么使用这个2*2子图的“桌面”呢?

经过分析,发现把bar的位置参数ax=[]坐标设置完整就OK了

data.plot.bar(ax=axes[1,1], color='b', alpha = 0.5)
data.plot.barh(ax=axes[0,1], color='k', alpha=0.5)

分析:plot.bar(ax=[]),参数ax=[] 来设定bar的子图坐标。

  • 当ax=[1],即1个参数时代码可执行,是因为“桌面”plt.subplots(2, 1)为2*1个子图,即上下2个区域/子图。
  • 当ax=[0,1],即2个参数时,是因为“桌面”plt.subplots(2, 2)为2*2个子图,此时不再是单列M行个区域/子图,只有完整的2各参数坐标才能定义出来图表所在的位置。

现在,运行新代码结果如下:

猜你喜欢

转载自blog.csdn.net/htuhxf/article/details/82986440