Specify figure size in centimeter in matplotlib

前端 未结 3 1688
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 23:00

I am wondering whether you can specify the size of a figure in matplotlib in centimeter. At the moment I write:

def cm2inch(value):
    return value/2.54

fi         


        
3条回答
  •  萌比男神i
    2020-12-05 23:05

    AFIK matplotlib has no conversion functions.

    If you often need to convert units, you could consider using pint. It offers also NumPy support.

    For your example you could do something like the following:

    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)
    

提交回复
热议问题