Python Matplotlib Plot:设置输出文件的纵横比(例如jpg)[重复]
Posted
技术标签:
【中文标题】Python Matplotlib Plot:设置输出文件的纵横比(例如jpg)[重复]【英文标题】:Python Matplotlib Plot: Set aspect ratio of output file (e.g. jpg) [duplicate] 【发布时间】:2022-01-01 05:24:46 【问题描述】:我正在尝试设置绘图的纵横比,但包括标题和轴标签。我知道 figsize 仅指轴。我已经尝试过 plt.tight_layout、plt.subplots_adjust 和 fig.set_size_inches 但没有一个能解决我的问题。我也尝试增加输入宽高比,测试输出比例是否符合规则。
这是一个最小的、可重现的例子:
最后,我需要一个 320mmx70mm(宽 x 高)的 .jpg 输出文件。所以纵横比应该是 320/70=4,57。目前 figsize 仅指轴,输出中的纵横比变为 1960px/523px = 3,75。我的目标是输出纵横比为 4,57。
fig = plt.figure(figsize=[320/25.4, 70/25.4])
ax = fig.add_axes([0,0,1,1])
langs = ['C', 'C++', 'Java', 'Python', 'php']
students = [23,17,35,29,12]
ax.bar(langs,students)
ax.set_title('Title', loc='left', fontdict=dict(fontsize=20, fontweight='bold'))
#plt.show()
plt.savefig('example.jpg', dpi=150, bbox_inches="tight")
【问题讨论】:
如果将pad_inches=0
添加到plt.savefig(...)
会怎样?
非常感谢,这似乎解决了我的问题。我一定忽略了这一点!
【参考方案1】:
import matplotlib.pyplot as plt
fig,ax = plt.subplots(figsize=[320/25.4, 70/25.4])
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.bar(langs,students)
ax.set_title('Title', loc='left', fontdict=dict(fontsize=20, fontweight='bold'))
plt.savefig('example.jpg', dpi=150, pad_inches=0)
输出 1888 x 412 像素:
【讨论】:
以上是关于Python Matplotlib Plot:设置输出文件的纵横比(例如jpg)[重复]的主要内容,如果未能解决你的问题,请参考以下文章
用Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围
python使用matplotlib可视化线图(line plot)并自定义设置可视化图像中没有网格线(remove grid line in matplotlib plot result)
python使用matplotlib可视化线图(line plot)并自定义设置可视化图像线条的类型(specify the line style of a plot in matplotlib)
python使用matplotlib可视化线图(line plot)并自定义设置可视化图像的大小(单位为英尺setting figure size of a plot in matplotlib)
python matplotlib.plot画图显示中文乱码的问题
python使用matplotlib可视化为可视化图像的X轴和Y轴设置自定义的轴标签(axis labels of matplotlib plot)