matplotlib实现一页多图

本文介绍了在matplotlib中创建一页多图的两种方法:直接指定和动态增加。直接指定通过`subplots`函数,动态增加则使用`subplot`或`subplot2grid`,详细解析了各个函数的用法及参数含义,帮助理解如何调整绘图区域和布局。
摘要由CSDN通过智能技术生成

欢迎关注”生信修炼手册”!

在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子模块

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值