Gar*_*ryS 7 python printing plot scaling matplotlib
我有许多图,其中 x 轴和 y 轴以厘米为单位,并且我已经在使用 axis('equal') 来确保正确的纵横比。我想打印出这些图,以便当我测量轴内的距离时,这些距离对应于真实世界的厘米。
也就是说,图中 3 个单位 (cm) 长的线应打印为 3 cm 长。(一个更复杂的例子是在 Matplotlib 中绘制一个标尺,然后将其打印出来以使用 /as/ a标尺。)我在 matlab 和 mathematica 中找到了解决方案,但不适用于 Matplotlib。有没有一个神奇的公式来实现这一目标?我相信它需要一个特殊的组合/排序: f igure(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.
| 归档时间: | 
 | 
| 查看次数: | 1884 次 | 
| 最近记录: |