How do you change the size of figures drawn with matplotlib?

后端 未结 19 3059
忘掉有多难
忘掉有多难 2020-11-21 06:01

How do you change the size of figure drawn with matplotlib?

相关标签:
19条回答
  • 2020-11-21 06:20

    I always use the following pattern:

    x_inches = 150*(1/25.4)     # [mm]*constant
    y_inches = x_inches*(0.8)
    dpi = 96
    
    fig = plt.figure(1, figsize = (x_inches,y_inches), dpi = dpi, constrained_layout = True)
    

    With this example you are able to set figure dimensions in inches or in milimiters and setting constrained_layout to True plots fill your figure without borders.

    0 讨论(0)
  • 2020-11-21 06:22

    You directly change the figure size by using

    plt.set_figsize(figure=(10, 10))
    
    0 讨论(0)
  • 2020-11-21 06:23

    Since Matplotlib isn't able to use the metric system natively, if you want to specify the size of your figure in a reasonable unit of length such as centimeters, you can do the following (code from gns-ank):

    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 you can use:

    plt.figure(figsize=cm2inch(21, 29.7))
    
    0 讨论(0)
  • 2020-11-21 06:25

    If you've already got the figure created you can quickly do this:

    fig = matplotlib.pyplot.gcf()
    fig.set_size_inches(18.5, 10.5)
    fig.savefig('test2png.png', dpi=100)
    

    To propagate the size change to an existing gui window add forward=True

    fig.set_size_inches(18.5, 10.5, forward=True)
    
    0 讨论(0)
  • 2020-11-21 06:26
    import matplotlib.pyplot as plt
    plt.figure(figsize=(20,10))
    plt.plot(x,y) ## This is your plot
    plt.show()
    

    You can also use:

    fig, ax = plt.subplots(figsize=(20, 10))
    
    0 讨论(0)
  • 2020-11-21 06:27

    USING plt.rcParams

    There is also this workaround in case you want to change the size without using the figure environment. So in case you are using plt.plot() for example, you can set a tuple with width and height.

    import matplotlib.pyplot as plt
    plt.rcParams["figure.figsize"] = (20,3)
    

    This is very useful when you plot inline (e.g. with IPython Notebook). As @asamaier noticed is preferable to not put this statement in the same cell of the imports statements.

    Conversion to cm

    The figsize tuple accepts inches so if you want to set it in centimetres you have to divide them by 2.54 have a look to this question.

    0 讨论(0)
提交回复
热议问题