gpt4 book ai didi

python - Matplotlib PDF 图不响应 figsize

转载 作者:太空狗 更新时间:2023-10-30 01:22:30 27 4
gpt4 key购买 nike

我希望使用以下代码调整子图的大小,使生成的 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()

关于python - Matplotlib PDF 图不响应 figsize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22079300/

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