遍历一个函数以绘制多个子图,Python [英] Looping through a function to plot several subplots, Python
问题描述
我有变量x
和y
def function(a,b):
x = x[(x>a)*(x<b)]
y = y[(y<a)*(y>b)]
# perform some fitting routine using curve_fit on x and y
fig = plt.figure()
ax = fig.add_subplot(111)
phist,xedge,yedge,img = ax.hist2d(x,y,bins=20,norm=LogNorm())
im = ax.imshow(phist,cmap=plt.cm.jet,norm=LogNorm(),aspect='auto')
fig.colorbar(im,ax=ax)
fig.show()
一切正常.但是我有6对不同的输入参数a
和b
.我想以某种方式使用循环调用function(a,b)
并将6个不同的x
和y
(对应于6个输入对)绘制为6个子图.
All works fine. But I have 6 pairs of different input parameters a
and b
. I would like to somehow call function(a,b)
using a loop and plot the six different x
and y
(corresponding to the 6 input pairs) as 6 subplots.
像我们一样
ax1 = fig.add_subplot(231) # x vs y for a1,b1
ax2 = fig.add_subplot(232) # x vs y for a2,b2
....
ax6 = fig.add_subplot(236) # x vs y for a6,b6
我想了解如何继续获取最终子图!
I would like to get an idea of how to proceed to get the final subplot!
我知道可以通过指定不同的变量来手动完成,例如对于第一个输入对a
和b
指定x1
和y1
,对于其他6个对(x2,y2...,x6,y6)
如此指定.但这将是一个非常冗长且令人困惑的代码.
I know that it can be done manually by specifying different variables, like x1
and y1
for the first input pair a
and b
and so on for the other 6 pairs (x2,y2...,x6,y6)
. But it will be a very lengthy and confusing code.
推荐答案
使用plt.subplots
代替plt.subplot
(请注意在末尾带有"s"). fig, axs = plt.subplots(2, 3)
将创建一个具有2x3组子图的图形,其中fig
是图形,而axs
是2x3 numpy数组,其中每个元素是与图形中相同位置的轴相对应的轴对象(因此axs[1, 2]
是右下轴).
Use plt.subplots
instead of plt.subplot
(note the "s" at the end). fig, axs = plt.subplots(2, 3)
will create a figure with 2x3 group of subplots, where fig
is the figure, and axs
is a 2x3 numpy array where each element is the axis object corresponding to the axis in the same position in the figure (so axs[1, 2]
is the bottom-right axis).
然后您可以使用一对循环遍历每一行,然后遍历该行中的每个轴:
You can then either use a pair of loops to loop over each row then each axis in that row:
fig, axs = plt.subplots(2, 3)
for i, row in enumerate(axs):
for j, ax in enumerate(row):
ax.imshow(foo[i, j])
fig.show()
或者您可以使用ravel
展平行以及您想从中获取数据的任何内容:
Or you can use ravel
to flatten the rows and whatever you want to get the data from:
fig, axs = plt.subplots(2, 3)
foor = foo.ravel()
for i, ax in enumerate(axs.ravel()):
ax.imshow(foor[i])
fig.show()
请注意,ravel
是视图,而不是副本,因此不会占用任何额外的内存.
Note that ravel
is a view, not a copy, so this won't take any additional memory.
这篇关于遍历一个函数以绘制多个子图,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!