45
votes

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

fig = plt.figure(figsize=(cm2inch(12.8), cm2inch(9.6)))

But is there a native approach?

4
I think your approach is good. Matplotlib does not have a native systems to handle units.David Zwicker
That's disappointing, it is a bit annoying to use a conversion for this kind of functionality. Though, there more important things to implement in mpl ;)HyperCube
why don't you do a pull request at matplotlib adding this function?Francesco Montesano
I think mpl only takes inches because internally resolutions are all stored as dpi.tacaswell

4 Answers

32
votes

This is not an answer to a question ''Is there a native way?'', but I think, that there is a more elegant way:

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)

Then one can issue plt.figure(figsize=cm2inch(12.8, 9.6)), which I think is a much cleaner way. The implementation also allows us to use cm2inch((12.8, 9.6)), which I personally do not prefer, but some people may do.


EDIT: Even though there is no way of doing this natively at the moment, I found a discussion here.

17
votes

I have submitted a pull request to the matplotlib repo on GitHub to include set_size_cm and get_size_cm features for figures (https://github.com/matplotlib/matplotlib/pull/5104)

If it is accepted, that should allow you to use a native approach to size-setting in centimeters.

1
votes

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)
0
votes

I think the solution provided here is also helpful. So, in your case,

cm = 1/2.54  # centimeters in inches
plt.figure(figsize=(12.8*cm, 9.6*cm))