####前言
在看Matplotlib,把自己理解的记录一下。
####正文
在 [Matplotlib Simple Plot][1] 的代码中,有这样一行:
fig, ax = plt.subplots()
plt.subplots()
返回一个 Figure实例fig 和一个 AxesSubplot实例ax 。这个很好理解,fig代表整个图像,ax代表坐标轴和画的图。
但是,将上述代码改为
fig, ax = plt.subplots(2,3)
时fig依旧是Figure实例,ax就变成ndarray了,显示一下fig:
其实ax很好理解:
我们看一下ax的元素是什么:
print (ax)
#输出:
[[<matplotlib.axes._subplots.AxesSubplot object at 0x000000CED4AEB5C0>
<matplotlib.axes._subplots.AxesSubplot object at 0x000000CECD469630>
<matplotlib.axes._subplots.AxesSubplot object at 0x000000CECD27C898>]
[<matplotlib.axes._subplots.AxesSubplot object at 0x000000CED4779CF8>
<matplotlib.axes._subplots.AxesSubplot object at 0x000000CECD4477B8>
<matplotlib.axes._subplots.AxesSubplot object at 0x000000CECD1BC748>]]
说明ax是保存 AxesSubplot实例 的 ndarray数组。
看一下ax中的元素:
print(ax[0][0])
print(ax[0][1])
print(ax[0][2])
print(ax[1][0])
print(ax[1][1])
print(ax[1][2])
#输出:
Axes(0.125,0.536818;0.227941x0.343182)
Axes(0.398529,0.536818;0.227941x0.343182)
Axes(0.672059,0.536818;0.227941x0.343182)
Axes(0.125,0.125;0.227941x0.343182)
Axes(0.398529,0.125;0.227941x0.343182)
Axes(0.672059,0.125;0.227941x0.343182)
我们在将上述Axes画在一个图中:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(
patches.Rectangle(
(0.125,0.536818), # (x,y)
0.227941, # width
0.343182, # height
)
)
ax1.add_patch(
patches.Rectangle(
(0.398529,0.536818), # (x,y)
0.227941, # width
0.343182, # height
)
)
ax1.add_patch(
patches.Rectangle(
(0.672059,0.536818), # (x,y)
0.227941, # width
0.343182, # height
)
)
ax1.add_patch(
patches.Rectangle(
(0.125,0.125), # (x,y)
0.227941, # width
0.343182, # height
)
)
ax1.add_patch(
patches.Rectangle(
(0.398529,0.125), # (x,y)
0.227941, # width
0.343182, # height
)
)
ax1.add_patch(
patches.Rectangle(
(0.672059,0.125), # (x,y)
0.227941, # width
0.343182, # height
)
)
# fig1.savefig('rect1.png', dpi=90, bbox_inches='tight')
plt.show()
输出:
这样就可以诠释plt.subplots
的返回值了。
完。
[1]: https://matplotlib.org/gallery/lines_bars_and_markers/simple_plot.html