我有许多图,其中 x 轴和 y 轴以厘米为单位,并且我已经在使用 axis('equal') 来确保适当的纵横比。我想打印出这些图,以便在我测量坐标轴内的距离时,这些距离对应于真实世界的厘米。
也就是说,绘图中长度为 3 个单位 (cm) 的线应打印为 3 cm 长。 (一个更复杂的例子是在 Matplotlib 中绘制一个标尺,然后将其打印出来以用作/作为/标尺。)我在 matlab 和 mathematica 中找到了解决方案,但在 Matplotlib 中找不到。有没有神奇的公式可以实现这一目标?我相信它需要一个特殊的组合/排序:figure(figsize=??), axis('equal')
, fig.canvas.draw()
, fig.savefig('filename',format="??")
,可能是一些带有 fig.bbox
参数的数学运算,可能还有一个或多个 dpi 设置。我尝试了很多组合,但没有找到正确的组合。也许有一种更简单的方法......
最佳答案
考虑这个例子。我在其中以厘米为单位准确指定轴的尺寸。 matplotlib 以英寸为单位工作,所以我转换为英寸。然后我还用特定的 dpi (128) 保存它,以便它与我的显示器中的设计尺寸相匹配。这当然因每个显示器而异。我通过反复试验发现,即使可能有其他方法。那么这里的代码:
left_margin = 1. # cm
right_margin = 1. # cm
figure_width = 10. # cm
figure_height = 7. # cm
top_margin = 1. # cm
bottom_margin = 1. # cm
box_width = left_margin + figure_width + right_margin # cm
box_height = top_margin + figure_height + bottom_margin # cm
cm2inch = 1/2.54 # inch per cm
# specifying the width and the height of the box in inches
fig = figure(figsize=(box_width*cm2inch,box_height*cm2inch))
ax = fig.add_subplot(111)
ax.plot([1,2,3])
fig.subplots_adjust(left = left_margin / box_width,
bottom = bottom_margin / box_height,
right = 1. - right_margin / box_width,
top = 1. - top_margin / box_height,
)
fig.savefig('ten_x_seven_cm.png', dpi=128)
# dpi = 128 is what works in my display for matching the designed dimensions.
关于python - 使用 matplotlib,如何打印 "actual size"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29400116/