仅为保存的图更改 Spyder 和 Matplotlib 图形大小

Change Spyder and Matplotlib figure size for saved plots only

我想在 Spyders IPython 控制台中以一种尺寸查看 matplotlib 图,并将图形以不同尺寸保存到多页 PDF。

目前我设置的图形尺寸如下:

plt.rc('axes', grid=True)
plt.rc('figure', figsize=(12, 8))
plt.rc('legend', fancybox=True, framealpha=1)

然后我绘制了一些图形并将它们保存到列表中,以便稍后保存 PDF。单独使用时效果很好。这些图的大小适合在 Spyder IPython 控制台中查看。

在我的脚本末尾,我有一个循环来遍历我想要保存的每个图形。在这里我想准确地设置布局和图形大小,以便在 A3 纸上更好地打印。

with PdfPages('multi.pdf') as pdf:
    for fig in figs:
        fig.tight_layout()
        fig.set_size_inches(420/25.4, 297/25.4)
        pdf.savefig(figure=fig)

输出的 PDF 就像我想要的那样,但问题出在 Spyder 中显示的图表上。在保存时更改图形大小也会影响在 Spyder 中查看的图。使用 A3 的大小会使图太大。

所以问题是:如何在不改变 Spyder 中显示的图形大小的情况下更改保存的 PDF 图形的大小?

正如@ImportanceOfBeingErnest 所建议的那样,保存后将图形大小改回原来的大小应该会起作用,并且可能会解决您的问题。

但是,根据您的具体问题,您可能会遇到缩放问题,因为 pdf 中保存的图形大小比 IPython 中显示的图形大小大得多安慰。如果您缩放所有内容以使其在 pdf 上看起来很棒,那么可能 IPython 中的所有内容看起来都太大了,如下例所示:

如果您不需要在 IPython 中交互绘图,一个解决方案可能是生成适合 pdf 的图形,并在 [=23] 中显示它们的缩放位图版本=]控制台如下代码所示:

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
from IPython.display import Image, display
try:  # Python 2
    from cStringIO import StringIO as BytesIO
except ImportError:  # Python 3
    from io import BytesIO

# Generate a matplotlib figures that looks good on A3 format :

fig, ax = plt.subplots()
ax.plot(np.random.rand(150), np.random.rand(150), 'o', color='0.35', ms=25,
        alpha=0.85)

ax.set_ylabel('ylabel', fontsize=46, labelpad=25)
ax.set_xlabel('xlabel', fontsize=46, labelpad=25)
ax.tick_params(axis='both', which='major', labelsize=30, pad=15,
               direction='out', top=False, right=False, width=3, length=10)
for loc in ax.spines:
    ax.spines[loc].set_linewidth(3)

# Save figure to pdf in A3 format:

w, h = 420/25.4, 297/25.4
with PdfPages('multi.pdf') as pdf:
    fig.set_size_inches(w, h)
    fig.tight_layout()
    pdf.savefig(figure=fig)
    plt.close(fig)

# Display in Ipython a sclaled bitmap using a buffer to save the png :

buf = BytesIO()
fig.savefig(buf, format='png', dpi=90)
display(Image(data=buf.getvalue(), format='png', width=450, height=450*h/w,
              unconfined=True))

在 IPython 控制台中显示为:

感谢@ImportanceOfBeingErnest 指出解决方案。

我采用了一种解决方案,允许我在开始时根据自己的喜好设置 plt.rc,然后在将数字导出为 PDF 后恢复为设置值。

首先我设置了我使用的值:

plt.rc('axes', grid=True)
plt.rc('figure', figsize=(12, 8))
plt.rc('legend', fancybox=True, framealpha=1)

有了这些,我可以只用默认值绘制我需要的东西。然后我创建 PDF:

with PdfPages('multi.pdf') as pdf:
    for fig in figs:
        fig.set_size_inches(420/25.4, 297/25.4)
        pdf.savefig(figure=fig, bbox_inches='tight')
        fig.set_size_inches(plt.rcParams.get('figure.figsize'))

有了这个我可以只在导出的图形上得到 fig.tight_layout() 并将图形大小恢复到之前设置的默认值。