遍历2d子图,就好像是一维 [英] loop over 2d subplot as if it's a 1-D

查看:84
本文介绍了遍历2d子图,就好像是一维的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用子图来绘制许多数据,但我没有遇到麻烦,但是我想知道是否有一种方便的方法可以做到这一点.

I'm trying to plot many data using subplots and I'm NOT in trouble but I'm wondering if there is a convenience method to do this.

下面是示例代码.

import numpy as np    
import math 
import matplotlib.pyplot as plt

quantities=["sam_mvir","mvir","rvir","rs","vrms","vmax"
,"jx","jy","jz","spin","m200b","m200c","m500c","m2500c"
,"xoff","voff","btoc","ctoa","ax","ay","az"]

# len(quantities) = 21, just to make the second loop expression 
# shorter in this post.

ncol = 5
nrow = math.ceil(21 / ncol)

fig, axes = plt.subplots(nrows = nrow, ncols=ncol, figsize=(8,6))

for i in range(nrow):
    for j in range(((21-i*5)>5)*5 + ((21-i*5)<5)*(21%5)):
        axes[i, j].plot(tree[quantities[i*ncol + j]]) 
        axes[i, j].set_title(quantities[i*ncol + j])

此代码循环遍历2D阵列的子图,并在第21个图上停止,从而使4个面板为空. 我的问题是,是否有任何内置方法可以执行此任务? 例如,制作2D子图数组并将其展平"为1D,然后在0D到20之间循环1D数组.

This code loops over a 2D array of subplots and stops at the 21st plot leaving 4 panels empty. My question is that, is there any built-in method to do this task? For example, make 2D subplot array and "flatten" the array into 1D then loop over 1D array through 0 to 20.

第二个range()中的表达式非常难看.我认为我不会使用此代码. 我认为微不足道的方法是计算地块数量,如果count> 21,则中断. 但是我只是想知道是否有更好的方法.

The expression in the second range() is very ugly. I don't think I'm going to use this code. I think the trivial way is to count the number of plots and break if count > 21. But I just wonder if there is a better (or fancy) way.

推荐答案

与其使用plt.subplots预先创建子图,不如使用plt.subplot(nrows, ncols, number)进行创建.下面的小示例显示了如何执行此操作.它创建了一个3x3的图形阵列,并且仅绘制了前6个.

Rather than creating your subplots in advance using plt.subplots, just create them as you go using plt.subplot(nrows, ncols, number). The small example below shows how to do it. It's created a 3x3 array of plots and only plotted the first 6.

import numpy as np
import matplotlib.pyplot as plt

nrows, ncols = 3, 3

x = np.linspace(0,10,100)

fig = plt.figure()    
for i in range(1,7):
    ax = fig.add_subplot(nrows, ncols, i)
    ax.plot(x, x**i)

plt.show()

您当然可以通过执行plt.subplot(nrows, ncols, i)来填充最后三个,但不要在其中调用任何绘图(如果那是您想要的).

You could fill the final three in of course by doing plt.subplot(nrows, ncols, i) but not calling any plotting in there (if that's what you wanted).

import numpy as np
import matplotlib.pyplot as plt

nrows, ncols = 3, 3

x = np.linspace(0,10,100)

fig = plt.figure()    
for i in range(1,10):
    ax = fig.add_subplot(nrows, ncols, i)
    if i < 7:
        ax.plot(x, x**i)

plt.show()

您可能还喜欢 GridSpec 的外观.

You may also like the look of GridSpec.

这篇关于遍历2d子图,就好像是一维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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