Specify figure size in centimeter in matplotlib
我想知道您是否可以在matplotlib中以厘米为单位指定图形的大小。目前,我写道:
1 2 3 4 | def cm2inch(value): return value/2.54 fig = plt.figure(figsize=(cm2inch(12.8), cm2inch(9.6))) |
但是有本机的方法吗?
这不是对"是否存在本机方式?"的回答,但我认为,还有一种更优雅的方式:
1 2 3 4 5 6 | 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) |
然后可以发布
编辑:尽管目前尚无办法在本地进行此操作,但我在这里找到了讨论。
我已向GitHub上的matplotlib存储库提交了拉取请求,以包含数字的set_size_cm和get_size_cm功能(https://github.com/matplotlib/matplotlib/pull/5104)
如果接受,则应允许您使用本机方法以厘米为单位设置大小。
AFIK
如果您经常需要转换单位,则可以考虑使用品脱。它还提供
对于您的示例,您可以执行以下操作:
1 2 3 4 5 6 7 8 | 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) |