aim*_*aim 8 python customization matplotlib subplot
我试图制作一个包含7个子图的情节.目前我正在绘制两个列,一个有四个图,另一个有三个,就像这样:
我正在按照以下方式构建这个情节:
#! /usr/bin/env python
import numpy as plotting
import matplotlib
from pylab import *
x = np.random.rand(20)
y = np.random.rand(20)
fig = figure(figsize=(6.5,12))
subplots_adjust(wspace=0.2,hspace=0.2)
iplot = 420
for i in range(7):
iplot += 1
ax = fig.add_subplot(iplot)
ax.plot(x,y,'ko')
ax.set_xlabel("x")
ax.set_ylabel("y")
savefig("subplots_example.png",bbox_inches='tight')
Run Code Online (Sandbox Code Playgroud)
但是,对于发布我认为这看起来有点难看 - 我想要做的是将最后一个子图移动到两列之间的中心.那么,调整最后一个子图的位置以使其居中的最佳方法是什么?即,在3X2网格中有前6个子图,下面的最后一个子图在两列之间居中.如果可能的话,我希望能够保持for
循环,以便我可以简单地使用:
if i == 6:
# do something to reposition/centre this plot
Run Code Online (Sandbox Code Playgroud)
谢谢,
亚历克斯
tac*_*ell 11
使用带有4x4网格的网格规格(doc),并使每个绘图跨越2列,如下所示:
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(4, 4)
ax1 = plt.subplot(gs[0, 0:2])
ax2 = plt.subplot(gs[0,2:])
ax3 = plt.subplot(gs[1,0:2])
ax4 = plt.subplot(gs[1,2:])
ax5 = plt.subplot(gs[2,0:2])
ax6 = plt.subplot(gs[2,2:])
ax7 = plt.subplot(gs[3,1:3])
fig = gcf()
gs.tight_layout(fig)
ax_lst = [ax1,ax2,ax3,ax4,ax5,ax6,ax7]
Run Code Online (Sandbox Code Playgroud)
如果你想保持for循环,你可以用你的情节来安排subplot2grid
,这允许一个colspan
参数:
#! /usr/bin/env python
import numpy as plotting
import matplotlib
from pylab import *
x = np.random.rand(20)
y = np.random.rand(20)
fig = figure(figsize=(6.5,12))
subplots_adjust(wspace=0.2,hspace=0.2)
iplot = 420
for i in range(7):
iplot += 1
if i == 6:
ax = subplot2grid((4,8), (i/2, 2), colspan=4)
else:
# You can be fancy and use subplot2grid for each plot, which dosen't
# require keeping the iplot variable:
# ax = subplot2grid((4,2), (i/2,i%2))
# Or you can keep using add_subplot, which may be simpler:
ax = fig.add_subplot(iplot)
ax.plot(x,y,'ko')
ax.set_xlabel("x")
ax.set_ylabel("y")
savefig("subplots_example.png",bbox_inches='tight')
Run Code Online (Sandbox Code Playgroud)