使用pyplot创建绘图网格

时间:2016-09-23 11:46:26

标签: python matplotlib plot

我是python的新手,在使用pyplot绘图时遇到了一些困难。我的目标是在Juypter Notebook中绘制一个内联网格(%pylab inline)。

我编写了一个函数plot_CV,它绘制了对某些x的多项式次数的交叉验证erorr,其中在惩罚程度(lambda)应该变化的情况下。最终lambda中有10个元素,它们由plot_CV中的第一个参数控制。所以

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1) 
ax1 = plot_CV(1,CV_ve=CV_ve)

给出

enter image description here

现在我想我必须使用add_subplot来创建一个情节网格,如

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1 = plot_CV(1,CV_ve=CV_ve)
ax2 = fig.add_subplot(2,2,2)
ax2 = plot_CV(2,CV_ve=CV_ve)
ax3 = fig.add_subplot(2,2,3)
ax3 = plot_CV(3,CV_ve=CV_ve)
ax4 = fig.add_subplot(2,2,4)
ax4 = plot_CV(4,CV_ve=CV_ve)
plt.show()

enter image description here

但是,如果我继续这样做,则图表会变得越来越小,并开始在x和y标签上重叠。这是一张3乘3图的图片。

enter image description here

有没有办法均匀地分隔地块,以便它们不会重叠并更好地利用Jupyter笔记本中的水平和垂直直线空间?为了说明这一点,这里是jupyter的截图:

enter image description here

最后注意事项:我仍然需要添加一个标题或注释,其中包含plot_CV中使用的当前lambda级别。

编辑:根据建议使用紧密布局,提供:

enter image description here

编辑2 :使用fig.set_figheightfig.set_figwidth我最终可以使用全长和高度。

enter image description here

1 个答案:

答案 0 :(得分:4)

对您的问题的第一个建议是看看" Tight Layout guide"对于matplotlib。

他们有一个看起来与你的情况非常相似的例子。他们也有考虑轴标签和情节标题的例子和建议。

您还可以使用matplotlib.figure类中的图来控制所有数字大小。

图(figsize =(x,y))

figsize:x,y(英寸)

编辑:

以下是我从matplotlib网站上提取并添加到:

的示例

fig.set_figheight(15) fig.set_figwidth(15)

import matplotlib.pyplot as plt

plt.rcParams['savefig.facecolor'] = "0.8"

def example_plot(ax, fontsize=12):
     ax.plot([1, 2])
     ax.locator_params(nbins=3)
     ax.set_xlabel('x-label', fontsize=fontsize)
     ax.set_ylabel('y-label', fontsize=fontsize)
     ax.set_title('Title', fontsize=fontsize)

plt.close('all')
fig = plt.figure()

fig.set_figheight(15)
fig.set_figwidth(15)


ax1 = plt.subplot2grid((3, 3), (0, 0))
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)

example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)

plt.tight_layout()

您可以通过这种方式使用tight_layout来实现子图的填充:

plt.tight_layout(pad = 0.4,w_pad = 0.5,h_pad = 1.0)

通过这种方式,您可以使子图不会进一步挤在一起。

有一个好的!

相关问题