欢迎关注”生信修炼手册”!
在matplotlib中,实现一页多图有以下两种方式
1. 直接指定
2. 动态增加
直接指定是在创建figure的时候,就直接定义好多个axes的排列方式;动态增加则是根据需要在figure上添加axes。下面来具体看下用法
1. 直接指定
直接指定可以通过pyplot子模块的subplots函数来实现,基本用法如下
>>> fig, axes = plt.subplots()
>>> axes
<matplotlib.axes._subplots.AxesSubplot object at 0x0A149E68>
>>> fig, axes = plt.subplots(2,2)
>>> axes
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x0106DBE0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x01087580>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x01099808>,
<matplotlib.axes._subplots.AxesSubplot object at 0x010BB1F0>]],
dtype=object)
>>> axes[0, 0]
<matplotlib.axes._subplots.AxesSubplot object at 0x0106DBE0>
>>> axes[0, 1]
<matplotlib.axes._subplots.AxesSubplot object at 0x01087580>
>>> axes[1, 0]
<matplotlib.axes._subplots.AxesSubplot object at 0x01099808>
>>> axes[1, 1]
<matplotlib.axes._subplots.AxesSubplot object at 0x010BB1F0>
不添加任何参数的情况下,生成包含了1个axes的figure对象,也可以通过指定nrows和ncols参数来生成多个axes的figure,然后通过数组下标来访问对应的axes对象。实际使用中,可以通过解列表的形式提高编码效率,代码如下
>>> fig, (ax1, ax2) = plt.subplots(1, 2)
>>> fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
这种方式生成的每个axes都是大小相同的,代码如下
>>> fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
>>> ax1.plot([1,2,3,4])
>>> ax2.bar(x = [1, 2, 3, 4], height = [4, 2, 3, 1])
>>> ax3.hist(x = np.random.normal(size=1000), bins=50)
>>> ax4.scatter(x= np.random.randn(10), y=np.random.randn(10),s=40 * np.arange(10),c=np.random.randn(10))
>>> plt.show()
输出结果如下
2. 动态指定
动态指定是在生成新的axes对象的同时,指定其排列的位置,通过pyplot子模块