【发布时间】:2021-06-08 08:49:24
【问题描述】:
我需要准确设置图表的维度。我试过这个,但结果不是我所期望的(如果我设置了 px 和 cm)。成瘾,我想知道如何正确导出图像。感谢您的帮助!
import numpy as np
plt.rcParams['figure.dpi']=100
# create data
x = ['A', 'B', 'C', 'D']
y1 = np.array([10, 20, 10, 30])
y2 = np.array([20, 25, 15, 25])
y3 = np.array([12, 15, 19, 6])
y4 = np.array([10, 29, 13, 19])
# plot bars in stack manner
cm = 1/2.54 # centimeters in inches
px = 1/plt.rcParams['figure.dpi'] # pixel in inches
plt.figure(figsize=(800*px,1000*px))
plt.bar(x, y1, color='r')
plt.bar(x, y2, bottom=y1, color='b')
plt.bar(x, y3, bottom=y1+y2, color='y')
plt.bar(x, y4, bottom=y1+y2+y3, color='g')
plt.xlabel("Teams")
plt.ylabel("Score")
plt.legend(["Round 1", "Round 2", "Round 3", "Round 4"])
plt.title("Scores by Teams in 4 Rounds")
plt.show()
预期尺寸:800 像素 x 1000 像素,dpi= 100 我在这里附上导出图像的 Photoshop 截图 Not correct dimensions!
【问题讨论】:
-
确切地说,你是如何保存你的图形的,从哪个后端保存的,你是否使用自定义的 rcParams?您声明的尺寸甚至没有正确的 8:10 纵横比,所以您在做一些奇怪的事情,我最好的猜测是您正在调用
savefig(fname, bbox_inches='tight') -
我发布了我写的所有代码。考虑到我是初学者,所以可能我做错了什么。 :) 我想更清楚一点:我需要编写一个代码,让我导出带有我想要的尺寸(以像素为单位)的图表。
-
你后来检查的 png 是如何保存的?
-
我只能通过右键单击图表并选择“将图像另存为”来保存它...我也尝试使用
plt.savefig(fname, bbox_inches='tight'),但它仍然不起作用。 -
执行 plt.savefig(fname, dpi=100)。右键单击图像(我假设在某种笔记本中?)不会返回一个漂亮的图像。
标签: matplotlib bar-chart dpi savefig inches