rus*_*ton 21 python matplotlib subplot
我是Python的新手,来自更Matlab的观点.我试图制作一系列2 x 5面板contourf子图.到目前为止,我的方法是将我的Matlab代码转换(在某种程度上)到Python并在循环中绘制我的子图.代码的相关部分如下所示:
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 250+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Run Code Online (Sandbox Code Playgroud)
作为这个论坛的新手,我似乎不允许附加结果图像.但是,通过我在代码中的索引作为'temp',2 x 5面板的最终布局是:
251 - 252 - 253 - 254 - 255
256 - 257 - 258 - 259 - 250
Run Code Online (Sandbox Code Playgroud)
但是,我想要的是
250 - 251 - 252 - 253 - 254
255 - 256 - 257 - 258 - 259
Run Code Online (Sandbox Code Playgroud)
也就是说,第一个面板(250)出现在我认为应该是259的最后位置.251似乎是我想要250放置的地方.它们似乎都处于正确的顺序,只是循环移动一个.
我知道这将是非常愚蠢的事情,但感谢你能给予的任何帮助.
先感谢您.
Rut*_*ies 53
使用您的代码和一些随机数据,这将工作:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(10):
axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
axs[i].set_title(str(250+i))
Run Code Online (Sandbox Code Playgroud)
布局当然有点乱,但这是因为你当前的设置(figsize,wspace等).

问题是索引subplot正在使用.子图从1开始计算!因此,您的代码需要阅读
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Run Code Online (Sandbox Code Playgroud)
请注意您计算的行的更改 temp
与Rutger Kassies提供的解决方案基本相同,但使用了更 Pythonic 的语法:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
data = np.arange(250, 260)
for ax, d in zip(axs.ravel(), data):
ax.contourf(np.random.rand(10,10), 5, cmap=plt.cm.Oranges)
ax.set_title(str(d))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64519 次 |
| 最近记录: |