在matplotlib中指定以厘米为单位的图形尺寸

Hyp*_*ube 32 matplotlib

我想知道你是否可以用厘米来指定matplotlib中数字的大小.目前我写道:

def cm2inch(value):
    return value/2.54

fig = plt.figure(figsize=(cm2inch(12.8), cm2inch(9.6)))
Run Code Online (Sandbox Code Playgroud)

但是有原生方法吗?

gns*_*ank 20

这不是一个问题的答案'' 是否有本土方式?'',但我认为,有一种更优雅的方式:

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)
Run Code Online (Sandbox Code Playgroud)

然后我们可以发布plt.figure(figsize=cm2inch(12.8, 9.6)),我认为这是一种更清洁的方式.实施也允许我们使用cm2inch((12.8, 9.6)),我个人不喜欢,但有些人可能会这样做.


编辑:即使目前没有办法原生这样做,我在这里找到了一个讨论.


Sam*_*ria 11

我认为这里提供的解决方案也很有帮助。所以,就你而言,

cm = 1/2.54  # centimeters in inches
plt.figure(figsize=(12.8*cm, 9.6*cm))
Run Code Online (Sandbox Code Playgroud)


Sam*_*uri 9

我已经向GitHub上的matplotlib repo提交了一个pull请求,包括数字的set_size_cm和get_size_cm功能(https://github.com/matplotlib/matplotlib/pull/5104)

如果它被接受,那么应该允许您使用原生方法进行厘米大小设置.

  • 6 年后,传奇仍在继续 https://github.com/matplotlib/matplotlib/issues/12402 (5认同)