【问题标题】:Set real dimensione of a Chart in Matplotlib在 Matplotlib 中设置图表的实际尺寸
【发布时间】: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


【解决方案1】:

Figure 构造函数接受默认为 80 dpi 的元组(以英寸为单位的数字)。你需要传递一个 dpi 参数来改变这个

from matplotlib.figure import Figure

fig = Figure(figsize=(5, 4), dpi=80)

以上是 5 英寸 x 4 英寸,80dpi,即 400 像素 x 320 像素

如果你想要 800 乘 1000,你可以这样做

fig = Figure(figsize=(8, 10), dpi=100)

导出图片很简单

fig.savefig("MatPlotLib_Graph.png", dpi = 100)

【讨论】:

  • 您好,谢谢,但还是不行……尺寸为 690x838 px
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 2012-08-24
相关资源
最近更新 更多