在matplotlib中以厘米指定图形大小
我在想,能不能在matplotlib里用厘米来指定图形的大小。目前我写的是:
def cm2inch(value):
return value/2.54
fig = plt.figure(figsize=(cm2inch(12.8), cm2inch(9.6)))
但是有没有更简单的方法呢?
4 个回答
1
据我所知,matplotlib并没有提供任何单位转换的功能。
如果你经常需要进行单位转换,可以考虑使用pint这个库。它还支持NumPy。
对于你的例子,你可以尝试下面的做法:
from pint import UnitRegistry
ureg = UnitRegistry()
width_cm, height_cm = (12.8 * ureg.centimeter, 9.6 * ureg.centimeter)
width_inch, height_inch = (width_cm.to(ureg.inch), height_cm.to(ureg.inch))
figsize_inch = (width_inch.magnitude, height_inch.magnitude)
fig = plt.figure(figsize=figsize_inch)
11
我觉得这里提供的解决方案 也很有帮助。所以,在你的情况下,
cm = 1/2.54 # centimeters in inches
plt.figure(figsize=(12.8*cm, 9.6*cm))
34
这不是对“有没有原生的方法?”这个问题的回答,但我觉得有一种更优雅的方式:
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
然后你可以使用 plt.figure(figsize=cm2inch(12.8, 9.6))
,我觉得这样写更简洁。这个实现还允许我们使用 cm2inch((12.8, 9.6))
,虽然我个人不太喜欢这样做,但有些人可能会喜欢。
虽然目前没有原生的方法可以做到这一点,但我找到了一段讨论,在这里。