Matplotlib PDF 绘图不响应 figsize



我希望以下代码调整子图的大小,以便生成的PDF宽5英寸,高8英寸。但无论我在figsize位中放入什么,生成的文件都是 8 英寸宽和 6 英寸高。我做错了什么?

import matplotlib.pyplot as plt
import matplotlib.gridspec as gs
fig = plt.Figure(figsize=(5,8))
fig.set_canvas(plt.gcf().canvas)
gs1 = gs.GridSpec(3,2)
gs1.update(wspace=0.4,hspace=0.4)
ax1 = plt.subplot(gs1[0,0])
ax2 = plt.subplot(gs1[0,1])
ax3 = plt.subplot(gs1[1,0])
ax4 = plt.subplot(gs1[1,1])
ax5 = plt.subplot(gs1[2,:])
ax1.plot([1,2,3],[4,5,6], 'k-')
fig.savefig("foo.pdf", format='pdf')

哎呀---编辑补充一点,我也试过fig.set_size_inches((5,8)),这似乎也没有任何效果。

您可能会

发现使用matplotlib.pyplot.figure更方便

在创建图形宽度后,尝试使用类似代码来配置图形宽度

fig = plt.figure()
fig.set_figheight(5)
fig.set_figwidth(8)

可能已经转换了尺寸,但这对我有用。这是一个从 matplotlib 文档中抄录的完整示例,其中包含对图形大小的修改。这也适用于 figure() 调用的 figsize 参数。

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
fig.set_figheight(10)
fig.set_figwidth(12)
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
        linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
fig.savefig("myfig.png", dpi=600) # useful for hi-res graphics
plt.show()

最新更新