我想用matplotlib生成出版物质量图。出于一致性的原因,我希望所有图表(轴)看起来都一样,尤其是尺寸。我浏览了许多教程,并提出了以下想法: 1.创建一个图并确定以英寸为单位的轴的高度 2.添加图例并确定图例的高度(以英寸为单位) 3.以图例高度(以英寸为单位)扩大图形高度 4.将新轴的高度缩小到原始轴的高度,以将图例保留在图形区域中
不幸的是,这无法正常工作。 关于守则有什么建议吗?
/** @noinspection PhpUnusedPrivateFieldInspection */
答案 0 :(得分:0)
通过使用savefig
的{{1}}参数,您似乎可以更轻松地获得所需的结果。
bbox_inches
如果您只需要保存图形就不需要它,那么此方法就可以使用。
plt.savefig("output.pdf", bbox_inches="tight", pad_inches=0)
请注意,如果您使用import matplotlib.pyplot as plt
import numpy as np
# GENERATE DATA
x = np.arange(-2.*np.pi,4.*np.pi,0.01)
sin_arr = [np.sin(x-dx) for dx in np.arange(0.,2.*np.pi,0.5)]
# SET FIGURE SIZE AND RCPARAMETERS
plt.rcParams.update( {'figure.figsize' : [5.90551197, 3.64980712]} )
fig, ax = plt.subplots()
for i,sin in enumerate(sin_arr):
ax.plot(x,sin,label=r'$\sin(x)$ '+str(i))
ax.set_xlabel(r'$\varepsilon$')
ax.set_ylabel(r'$\sigma$ in [MPa]', labelpad=15)
ax.set_xlim([0.,2.*np.pi])
# SHRINK PADDING
fig.tight_layout(pad=0)
# ADD LEGEND ON TOP OF AXES WITHOUT CHANGING AXES SIZE
legend = ax.legend( bbox_to_anchor=(0., 1.02, 1., .102),
loc='lower left',
ncol=3,
borderaxespad=0.,mode="expand" )
plt.savefig("output.pdf", bbox_inches="tight", pad_inches=0)
,则如果使用不同的x或y标签(例如,有时它们包含大写字母或低于基线的字母,例如“ p ”或“ g”)。在这种情况下,最好手动确定一些参数,并用
plt.tight_layout
tight_layout
或给定使用的字体大小的其他参数对您有用。
因此,轴尺寸恒定的问题很容易解决。倒数会更复杂。具有恒定的图形大小,但收缩轴以使图形仍可容纳图例。这将在问题Creating figure with exact size and no padding (and legend outside the axes)
中显示