gpt4 book ai didi

python - 使用 pyplot 创建绘图网格

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:50 26 4
gpt4 key购买 nike

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

我编写了一个函数 plot_CV,它绘制了一些 x 的多项式次数的交叉验证误差,其中惩罚程度 (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 x 3 图的图片。

enter image description here

有没有办法让绘图均匀分布,使它们不重叠并更好地利用 Jupyter Notebook 中的水平和垂直行内空间?为了说明这一点,这里有一张来自 jupyter 的截图:

enter image description here

最后说明:我仍然需要使用 plot_CV 中使用的当前 lambda 级别添加标题或注释。


编辑:使用建议的紧凑布局,给出:

enter image description here


编辑 2:使用 fig.set_figheightfig.set_figwidth 我终于可以使用可用的完整长度和高度。

enter image description here

最佳答案

针对您的问题的第一个建议是查看 matplotlib 的“Tight Layout guide”。

他们有一个看起来与您的情况非常相似的示例。他们还提供了考虑轴标签和绘图标题的示例和建议。

此外,您可以使用 matplotlib.figure 中的图来控制整体图的大小类(class)。

Figure(figsize = (x,y))

figsize: x,y (inches)

编辑:

这是我从 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)

这样你就可以防止你的子图进一步拥挤。

祝你好运!

关于python - 使用 pyplot 创建绘图网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39659998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com