【问题标题】:Is it possible to loop through the subplots of a matplotlib figure?是否可以遍历 matplotlib 图形的子图?
【发布时间】:2019-10-24 21:04:09
【问题描述】:

所以我有一个包含 16 个子图、4 列和 4 行的图形。首先,我专注于让位置 (0,0) 的子图正常工作(我想通了!),然后再继续让循环正常工作。

这就是我卡住的地方。这是我的代码的 matplotlib 部分的样子:

new_list = [one, two, three, four, five, six, seven, eight, nine, ten , eleven, twelve, 
    thirteen, fourteen, fifteen, sixteen]
color = ['blue','red']

for name in new_list:
    for row in range(0,subplot_shape[0]):
        for col in range(0,subplot_shape[1]):
            display.plot('total', 
                        currentname=name,
                        subplot_index=(row,col),
                        linestyle='-',
                        marker='.',
                        label="RG",
                        color=color[0])
            display.plot('new_total', 
                        currentname=name,
                        subplot_index=(row,col),
                        linestyle='-',
                        marker='.',
                        label="RG New",
                        color=color[1])
            display.axes[row][col].set_title(name + ' Total on ' + date)
            display.axes[row][col].legend()
            display.axes[row][col].autoscale(tight=False, axis='y')
            display.axes[row][col].set_xlim(xrng)

按照我目前的设置方式,所有内容都绘制在每个子图上。我不确定我做错了什么。

我希望每个子图的每个数据集的内容都以“new_list”命名。 (因此,subplot(0,0) 将具有数据集 1,subplot(0,1) 将具有数据集 2,依此类推。

【问题讨论】:

  • 这段代码中的“显示”是什么?这不是 matplotlib

标签: python for-loop matplotlib


【解决方案1】:

使用面向对象的 API:fig, axes = plt.subplots(nrows=4, ncols=4)

然后你可以遍历行/列,例如:

for row, axes_row in enumerate(axes):
    for col, ax in enumerate(axes_row): 
        # do your stuff
        ax.plot(...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 2016-05-16
    • 2020-11-02
    相关资源
    最近更新 更多