使用Gridspec绘制网格中的网格时的问题
我正在尝试在matplotlib中制作一个图形,这个图形里面有一个个小图,形成一个网格。我使用的是matplotlib 1.1.1和python 2.7.4。
我参考了这个文档页面上的示例:http://matplotlib.org/users/gridspec.html#a-complex-nested-gridspec-using-subplotspec
fig = plt.figure(figsize=(11, 10))
levels2=[2,8,32,64,128, 256, 512]
bins=100
def plotcmd(ax, x, y, bins, levels):
cmap=cm.Greys
cmap.set_gamma(0.8)
h, xe, ye = np.histogram2d(x, y, bins=70)
cont = ax.contourf(h.T, extent=[xe[0],xe[-1], ye[0],ye[-1]], levels=levels,
zorder=2, cmap=cmap)
cont = ax.contour(h.T, extent=[xe[0],xe[-1], ye[0],ye[-1]], levels=levels, zorder=3,
colors=('black', 'black', 'black','black'))
# set limits
plt.xlim(-1, 5)
plt.ylim(13, 2)
for i in xrange(4):
inner_grid = gridspec.GridSpecFromSubplotSpec(1, 3,
subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0)
for j in xrange(3):
ax = plt.Subplot(fig, inner_grid[j])
plotcmd(ax, data1[:,0]-data1[:,1], data1[:,1], bins, levels2)
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
这样应该能创建一个图形,里面有四个大面板,每个大面板里又有三个小面板。整体上差不多正确,但最后的图有两个问题:
1.) 最后的图,也就是当 i == 3 和 j == 2 时,似乎没有遵循我在 plotcmd 中设置的限制,就好像这些限制根本不存在一样。
2.) 在四个大面板的下面,居然还画了一个图。
我不明白,既然所有迹象都表明我在正确地遍历外部和内部的网格,为什么 x 和 y 的限制不会影响最后的图。
谢谢大家的帮助。
Alexa
1 个回答
0
根据tcaswell的建议,我把我的matplotlib版本升级到了1.3.2,不过这并没有解决gridspec的问题,但我还是找到了让它正常工作的办法。
我不太明白我之前的代码为什么会产生那样的效果,但当我把我的plotcmd函数改成这样:
def plotcmd(x, y, bins, levels, ax):
h, xe, ye = np.histogram2d(x, y, bins=bins)
ax.contourf(h.T, extent=[xe[0],xe[-1], ye[0],ye[-1]],
levels=levels, zorder=2, cmap=cmap)
ax.contour(h.T, extent=[xe[0],xe[-1], ye[0],ye[-1]],
levels=levels, colors=('black', 'black', 'black','black'))
ax.set_xlim(-1, 5)
ax.set_ylim(13, 2)
最后生成的图看起来不错。