在Matplotlib中循环创建子图? [英] Create subplots in Matplotlib in a loop?

查看:625
本文介绍了在Matplotlib中循环创建子图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码,它提供了一个接一个的漂亮图表(使用IPython-notebook和Pamps)

I am using this code which provides nice plots one after the next (using IPython-notebook & Pandas)

for subsm in subsl:
    H7, subsm = sumsubdesc2(table, subsm)   
    ax1=H7.plot()
    plt.title('Rolling 4q mean %s'%(subsm))
    ax1.set_title('Rolling 4q mean %s'%(subsm))
    ax1.set_ylim(100000,600000)

我想让图"2up"与下一个相邻,共3行(5个子图),不知道如何处理,因为所有子图示例似乎都是在对数据或数据进行子图绘制.特定的图和特定的网格位置.

I'd like to get the plots "2up" one next to the next for 3 rows total (5 subplots) can't figure out how to handle that since all the subplot examples seem to be for subplotting ether the data or specific plots and specific grid placement.

所以我不知道如何创建主图,然后子图绘制多个图(在本例中为5),其标题为两个图.

So I don't know how to create the main plot and then subplot a number of graphs (in this case 5) with titles as two-up?

编辑第二行代码,因为我省略了函数调用;-(

Edit line two of code since I left out the function call ;-(

推荐答案

这是您需要做的:

import math
import matplotlib.pylab as plt

nrows = int(math.ceil(len(subsl) / 2.))

fig, axs = plt.subplots(nrows, 2)

ylim = 100000, 600000
for ax, subsm in zip(axs.flat, subsl):
    H7, subsm = sumsubdesc2(table, subsm)
    H7.plot(ax=ax, title='Rolling 4q mean %s' % subsm)
    ax.set_ylim(ylim)

即使最短的迭代用完时会升高StopIteration,即使axs.size > len(subsl)也会起作用.请注意,axs.flat是在行顺序展平的axs数组上的迭代器.

This will work even if axs.size > len(subsl) since StopIteration is raised when the shortest iterable runs out. Note that axs.flat is an iterator over the row-order flattened axs array.

要隐藏最后一个未显示的图,请执行以下操作:

To hide the last plot that isn't showing, do this:

axs.flat[-1].set_visible(False)

更一般而言,对于axs.size - len(subsl)网格末尾的额外图,请执行以下操作:

More generally, for axs.size - len(subsl) extra plots at the end of the grid do:

for ax in axs.flat[axs.size - 1:len(subsl) - 1:-1]:
    ax.set_visible(False)

该切片看起来有些粗糙,所以我将解释:

That slice looks a little gnarly, so I'll explain:

数组axs具有axs.size元素. axs的展平版本的最后一个元素的索引为axs.size - 1. subsl具有len(subsl)个元素,并且对最后一个元素的索引也采用相同的推理.但是,我们需要从axs的最后一个元素移回最后一个 plotted 元素,因此我们需要以-1步进.

The array axs has axs.size elements. The index of the last element of the flattened version of axs is axs.size - 1. subsl has len(subsl) elements and the same reasoning applies about the index of the last element. But, we need to move back from the last element of axs to the last plotted element so we need to step by -1.

这篇关于在Matplotlib中循环创建子图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆