【问题标题】:How do you change the size of figures drawn with Matplotlib?如何更改使用 Matplotlib 绘制的图形的大小?
【发布时间】:2018-07-28 12:44:09
【问题描述】:

如何改变使用 Matplotlib 绘制的图形的大小?

【问题讨论】:

    标签: python graph matplotlib plot visualization


    【解决方案1】:

    以像素为单位设置精确图像大小的不同方法的比较

    这个答案将集中在:

    • savefig:如何保存到文件,而不仅仅是显示在屏幕上
    • 以像素为单位设置大小

    这里是我尝试过的一些方法的快速比较,图片显示了所提供的内容。

    当前状态总结:事情一团糟,不确定这是否是基本限制,或者如果用例没有得到开发人员的足够关注,我无法轻易找到关于此的上游讨论。

    不尝试设置图像尺寸的基准示例

    只是为了有个比较点:

    base.py

    #!/usr/bin/env python3
    
    import sys
    
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    fig, ax = plt.subplots()
    print('fig.dpi = {}'.format(fig.dpi))
    print('fig.get_size_inches() = ' + str(fig.get_size_inches())
    t = np.arange(-10., 10., 1.)
    plt.plot(t, t, '.')
    plt.plot(t, t**2, '.')
    ax.text(0., 60., 'Hello', fontdict=dict(size=25))
    plt.savefig('base.png', format='png')
    

    运行:

    ./base.py
    identify base.png
    

    输出:

    fig.dpi = 100.0
    fig.get_size_inches() = [6.4 4.8]
    base.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000
    

    到目前为止我最好的方法:plt.savefig(dpi=h/fig.get_size_inches()[1] 仅高度控制

    我认为这是我大部分时间都会使用的,因为它简单且可扩展:

    get_size.py

    #!/usr/bin/env python3
    
    import sys
    
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    height = int(sys.argv[1])
    fig, ax = plt.subplots()
    t = np.arange(-10., 10., 1.)
    plt.plot(t, t, '.')
    plt.plot(t, t**2, '.')
    ax.text(0., 60., 'Hello', fontdict=dict(size=25))
    plt.savefig(
        'get_size.png',
        format='png',
        dpi=height/fig.get_size_inches()[1]
    )
    

    运行:

    ./get_size.py 431
    

    输出:

    get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000
    

    ./get_size.py 1293
    

    输出:

    main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000
    

    我倾向于只设置高度,因为我通常最关心图像将在文本中间占据多少垂直空间。

    plt.savefig(bbox_inches='tight' 改变图片大小

    我总觉得图片周围留白太多,倾向于加bbox_inches='tight' from: Removing white space around a saved image

    但是,这可以通过裁剪图像来实现,并且您不会获得所需的尺寸。

    相反,在同一个问题中提出的另一种方法似乎效果很好:

    plt.tight_layout(pad=1)
    plt.savefig(...
    

    它给出了高度等于 431 的确切期望高度:

    固定高度,set_aspect,自动调整宽度和小边距

    Ermmm,set_aspect 又搞砸了,并阻止 plt.tight_layout 实际删除边距...这是一个重要的用例,我还没有很好的解决方案。

    提问于:How to obtain a fixed height in pixels, fixed data x/y aspect ratio and automatically remove remove horizontal whitespace margin in Matplotlib?

    plt.savefig(dpi=h/fig.get_size_inches()[1] + 宽度控制

    如果您真的需要除高度之外的特定宽度,这似乎可以正常工作:

    宽度.py

    #!/usr/bin/env python3
    
    import sys
    
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    h = int(sys.argv[1])
    w = int(sys.argv[2])
    fig, ax = plt.subplots()
    wi, hi = fig.get_size_inches()
    fig.set_size_inches(hi*(w/h), hi)
    t = np.arange(-10., 10., 1.)
    plt.plot(t, t, '.')
    plt.plot(t, t**2, '.')
    ax.text(0., 60., 'Hello', fontdict=dict(size=25))
    plt.savefig(
        'width.png',
        format='png',
        dpi=h/hi
    )
    

    运行:

    ./width.py 431 869
    

    输出:

    width.png PNG 869x431 869x431+0+0 8-bit sRGB 10965B 0.000u 0:00.000
    

    对于小宽度:

    ./width.py 431 869
    

    输出:

    width.png PNG 211x431 211x431+0+0 8-bit sRGB 6949B 0.000u 0:00.000
    

    所以看起来字体缩放是正确的,我们只是在标签被切断的非常小的宽度上遇到了一些麻烦,例如左上角的100

    我设法解决了 Removing white space around a saved image 的问题

    plt.tight_layout(pad=1)
    

    给出:

    width.png PNG 211x431 211x431+0+0 8-bit sRGB 7134B 0.000u 0:00.000
    

    从这里我们也看到tight_layout去掉了图片顶部的很多空白,所以我一般只是经常使用它。

    固定魔法基础高度,dpi fig.set_size_inchesplt.savefig(dpi= 缩放

    我相信这和上面提到的方法是等价的:https://stackoverflow.com/a/13714720/895245

    magic.py

    #!/usr/bin/env python3
    
    import sys
    
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    magic_height = 300
    w = int(sys.argv[1])
    h = int(sys.argv[2])
    dpi = 80
    fig, ax = plt.subplots(dpi=dpi)
    fig.set_size_inches(magic_height*w/(h*dpi), magic_height/dpi)
    t = np.arange(-10., 10., 1.)
    plt.plot(t, t, '.')
    plt.plot(t, t**2, '.')
    ax.text(0., 60., 'Hello', fontdict=dict(size=25))
    plt.savefig(
        'magic.png',
        format='png',
        dpi=h/magic_height*dpi,
    )
    

    运行:

    ./magic.py 431 231
    

    输出:

    magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000
    

    然后看看它是否可以很好地扩展:

    ./magic.py 1291 693
    

    输出:

    magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000
    

    所以我们看到这种方法也很有效。我唯一遇到的问题是您必须设置 magic_height 参数或等效参数。

    固定 DPI + set_size_inches

    这种方法给出了一个稍微错误的像素大小,并且很难无缝缩放所有内容。

    set_size_inches.py

    #!/usr/bin/env python3
    
    import sys
    
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    w = int(sys.argv[1])
    h = int(sys.argv[2])
    fig, ax = plt.subplots()
    fig.set_size_inches(w/fig.dpi, h/fig.dpi)
    t = np.arange(-10., 10., 1.)
    plt.plot(t, t, '.')
    plt.plot(t, t**2, '.')
    ax.text(
        0,
        60.,
        'Hello',
        # Keep font size fixed independently of DPI.
        # https://stackoverflow.com/questions/39395616/matplotlib-change-figsize-but-keep-fontsize-constant
        fontdict=dict(size=10*h/fig.dpi),
    )
    plt.savefig(
        'set_size_inches.png',
        format='png',
    )
    

    运行:

    ./set_size_inches.py 431 231
    

    输出:

    set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000
    

    所以高度稍微偏离了,图像:

    如果我把它放大 3 倍,像素大小也是正确的:

    ./set_size_inches.py 1291 693
    

    输出:

    set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000
    

    但是,我们从中了解到,要使这种方法很好地缩放,您需要使每个 DPI 相关设置与以英寸为单位的大小成比例。

    在前面的示例中,我们只使“Hello”文本成比例,它的高度确实保持在我们预期的 60 到 80 之间。但是我们没有这样做的所有东西看起来都很小,包括:

    • 坐标区的线宽
    • 勾选标签
    • 点标记

    SVG

    我找不到如何为 SVG 图像设置它,我的方法仅适用于 PNG,例如:

    get_size_svg.py

    #!/usr/bin/env python3
    
    import sys
    
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    height = int(sys.argv[1])
    fig, ax = plt.subplots()
    t = np.arange(-10., 10., 1.)
    plt.plot(t, t, '.')
    plt.plot(t, t**2, '.')
    ax.text(0., 60., 'Hello', fontdict=dict(size=25))
    plt.savefig(
        'get_size_svg.svg',
        format='svg',
        dpi=height/fig.get_size_inches()[1]
    )
    

    运行:

    ./get_size_svg.py 431
    

    并且生成的输出包含:

    <svg height="345.6pt" version="1.1" viewBox="0 0 460.8 345.6" width="460.8pt"
    

    并确定说:

    get_size_svg.svg SVG 614x461 614x461+0+0 8-bit sRGB 17094B 0.000u 0:00.000
    

    如果我在 Chromium 86 中打开它,浏览器调试工具鼠标图像悬停确认高度为 460.79。

    当然,由于 SVG 是一种矢量格式,理论上一切都应该按比例缩放,因此您可以在不损失分辨率的情况下转换为任何固定大小的格式,例如:

    inkscape -h 431 get_size_svg.svg -b FFF -e get_size_svg.png
    

    给出准确的高度:

    我在这里使用 Inkscape 而不是 Imagemagick 的 convert,因为您还需要使用 -density 来使用 ImageMagick 获得锐利的 SVG 大小调整:

    在 HTML 上设置 &lt;img height="" 也应该只适用于浏览器。

    在 matplotlib==3.2.2 上测试。

    【讨论】:

      【解决方案2】:
      import random
      import math
      import matplotlib.pyplot as plt
      start=-20
      end=20
      x=[v for v in range(start,end)]
      #sigmoid function
      def sigmoid(x):
          return 1/(1+math.exp(x))
      plt.figure(figsize=(8,5))#setting the figure size
      plt.scatter([abs(v) for v in x],[sigmoid(v) for v in x])
      plt.scatter(x,[sigmoid(sigmoid(v)) for v in x])
      

      【讨论】:

        【解决方案3】:

        如果你已经创建好了图形,可以使用figure.set_size_inches调整图形大小:

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

        要将大小更改传播到现有的 GUI 窗口,请添加 forward=True

        fig.set_size_inches(18.5, 10.5, forward=True)
        

        除了Erik Shilts mentioned in the comments,您还可以使用figure.set_dpi 来“[s]以每英寸点数为单位设置图形的分辨率”

        fig.set_dpi(100)
        

        【讨论】:

        • imshow 解决了我的问题,现在我在用plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0) 消除绘图区域周围的空间后使用此代码。
        • 同样,你可以运行fig.set_dpi(100)
        • 我在 ipython 3.7、matplotlib 3.0.3 下的 OS X 上使用它。我可以调整图形大小,但窗口不会调整大小(图形画布会调整,但窗口不会扩大或缩小以适应画布)。 forward=True 关键字参数在这个平台上似乎没有预期的效果。
        • 窗口调整大小对我不起作用。看起来 forward=True 是关键,但它没有解决它。事实证明它确实修复了它,我只是要小心调用 set_size_inches 的顺序。它需要在调用tight_layout() 之后调用。我在axes.bar 图上遇到了这个问题,而在常规图上却没有。
        【解决方案4】:

        这是我自己的一个例子。

        下面我已经给了你你的答案,我已经扩展了供你试验。

        另请注意,无花果尺寸值以英寸

        为单位
        import matplotlib.pyplot as plt
        
        data = [2,5,8,10,15] # Random data, can use existing data frame column
        
        fig, axs = plt.subplots(figsize = (20,6)) # This is your answer to resize the figure
        
        # The below will help you expand on your question and resize individual elements within your figure. Experiement with the below parameters.
        axs.set_title("Data", fontsize = 17.5)
        axs.tick_params(axis = 'x', labelsize = 14)
        axs.set_xlabel('X Label Here', size = 15)
        axs.tick_params(axis = 'y', labelsize =14)
        axs.set_ylabel('Y Label Here', size = 15)
        
        plt.plot(data)
        

        输出:

        【讨论】:

          【解决方案5】:

          如果您正在寻找一种方法来更改 Pandas 中的图形大小,您可以这样做:

          df['some_column'].plot(figsize=(10, 5))
          

          df 是 Pandas 数据框。或者,使用现有图形或坐标轴:

          fig, ax = plt.subplots(figsize=(10, 5))
          df['some_column'].plot(ax=ax)
          

          如果您想更改默认设置,您可以执行以下操作:

          import matplotlib
          
          matplotlib.rc('figure', figsize=(10, 5))
          

          有关更多详细信息,请查看文档:pd.DataFrame.plot

          【讨论】:

            【解决方案6】:

            这就是我使用自定义大小打印自定义图表的方式

            import matplotlib.pyplot as plt
            from matplotlib.pyplot import figure
            
            figure(figsize=(16, 8), dpi=80)
            plt.plot(x_test, color = 'red', label = 'Predicted Price')
            plt.plot(y_test, color = 'blue', label = 'Actual Price')
            plt.title('Dollar to PKR Prediction')
            plt.xlabel('Predicted Price')
            plt.ylabel('Actual Dollar Price')
            plt.legend()
            plt.show()
                       
            

            【讨论】:

              【解决方案7】:

              使用 plt.rcParams

              如果您想在不使用图形环境的情况下更改大小,也可以使用此解决方法。因此,如果您使用 plt.plot() 为例,您可以设置一个具有宽度和高度的元组。

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

              这在您内联绘图时非常有用(例如,使用IPython Notebook)。与asmaier noticed 一样,最好不要将此语句放在导入语句的同一单元格中。

              将全局图形大小重置为后续绘图的默认值:

              plt.rcParams["figure.figsize"] = plt.rcParamsDefault["figure.figsize"]
              

              转换为厘米

              figsize 元组接受英寸,所以如果你想以厘米为单位,你必须将它们除以 2.54。看看this question

              【讨论】:

              • 太棒了!对于设置一次并多次绘制也很有用。
              • 由于某种原因,这似乎不再适用于 Jupyter 笔记本(但曾经)。
              • @Ray 你能写出你的 Jupyter notebook 的版本以及它对我的行为吗
              • 为了让它工作,我需要在一个额外的单元格中调用plt.rcParams["figure.figsize"] = (20,3)。当我在与导入语句相同的单元格中调用它时,它会被忽略。
              • 要将后续绘图的全局图形大小重置为默认值,请使用plt.rcParams['figure.figsize'] = plt.rcParamsDefault['figure.figsize']
              【解决方案8】:

              以下内容肯定会起作用,但请确保在plt.plot(x,y)plt.pie() 等上方添加行plt.figure(figsize=(20,10))

              import matplotlib.pyplot as plt
              plt.figure(figsize=(20,10))
              plt.plot(x,y) ## This is your plot
              plt.show()
              

              复制代码from amalik2205

              【讨论】:

                【解决方案9】:

                使用这个:

                plt.figure(figsize=(width,height))
                

                widthheight 以英寸为单位。 如果未提供,则默认为rcParams["figure.figsize"] = [6.4, 4.8]。查看更多here

                【讨论】:

                  【解决方案10】:

                  我总是使用以下模式:

                  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)
                  

                  通过此示例,您可以以英寸或毫米为单位设置图形尺寸。将constrained_layout 设置为True 时,绘图会填充您的图形而没有边界。

                  【讨论】:

                    【解决方案11】:

                    概括和简化psihodelia's answer

                    如果您想将图形的当前大小更改一个因子sizefactor

                    import matplotlib.pyplot as plt
                    
                    # Here goes your code
                    
                    fig_size = plt.gcf().get_size_inches() # Get current size
                    sizefactor = 0.8 # Set a zoom factor
                    # Modify the current size by the factor
                    plt.gcf().set_size_inches(sizefactor * fig_size) 
                    

                    更改当前大小后,您可能需要微调 子图布局。您可以在图形窗口 GUI 中执行此操作,或通过命令 subplots_adjust

                    例如,

                    plt.subplots_adjust(left=0.16, bottom=0.19, top=0.82)
                    

                    【讨论】:

                      【解决方案12】:

                      另一种选择是使用 Matplotlib 中的 rc() 函数(单位为英寸):

                      import matplotlib
                      matplotlib.rc('figure', figsize=[10,5])
                      

                      【讨论】:

                      • 这非常有用,因为它可以全局分配大小。这样你就不需要为每个地块指定它。但是,更常见的是先执行import matplotlib.pyplot as plt,然后执行plt.rc('figure', figsize=(10,5))
                      【解决方案13】:

                      要将图形的大小增加 N 倍,您需要在 pl.show() 之前插入它:

                      N = 2
                      params = pl.gcf()
                      plSize = params.get_size_inches()
                      params.set_size_inches((plSize[0]*N, plSize[1]*N))
                      

                      它也适用于 IPython 笔记本。

                      【讨论】:

                        【解决方案14】:

                        即使在图形绘制完成后也会立即调整图形大小(至少使用 Qt4Agg/TkAgg - 但不是 Mac OS X - 使用 Matplotlib 1.4.0):

                        matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px)
                        

                        【讨论】:

                          【解决方案15】:

                          这对我很有效:

                          from matplotlib import pyplot as plt
                          
                          F = plt.gcf()
                          Size = F.get_size_inches()
                          F.set_size_inches(Size[0]*2, Size[1]*2, forward=True) # Set forward to True to resize window along with plot in figure.
                          plt.show() # Or plt.imshow(z_array) if using an animation, where z_array is a matrix or NumPy array
                          

                          这个论坛帖子也可能有帮助:Resizing figure windows

                          【讨论】:

                          • 窗口调整大小对我不起作用。看起来 forward=True 是关键,但它没有解决它。事实证明它确实修复了它,我只是要小心调用 set_size_inches 的顺序。它需要在调用tight_layout() 之后调用。我在axes.bar 图上遇到了这个问题,而在常规图上却没有。
                          【解决方案16】:

                          创建新图形时,您可以使用figsize 参数指定大小(以英寸为单位):

                          import matplotlib.pyplot as plt
                          fig = plt.figure(figsize=(w,h))
                          

                          如果您想修改现有图,请使用set_size_inches() 方法:

                          fig.set_size_inches(w,h)
                          

                          如果您想更改默认图形大小(6.4" x 4.8"),请使用"run commands" rc

                          plt.rc('figure', figsize=(w,h))
                          

                          【讨论】:

                            【解决方案17】:

                            figure 告诉你调用签名:

                            from matplotlib.pyplot import figure
                            
                            figure(figsize=(8, 6), dpi=80)
                            

                            figure(figsize=(1,1)) 将创建一个 80×80 像素的逐英寸图像,除非您还提供不同的 dpi 参数。

                            【讨论】:

                            • 如果你已经创建了图形,说它是'figure 1'(这是你使用 pyplot 时的默认值),你可以使用 figure(num=1, figsize=(8 , 6), ...) 来改变它的大小等。如果你使用 pyplot/pylab 和 show() 创建一个弹出窗口,你需要调用 figure(num=1,...) before 你绘制任何东西- pyplot/pylab 在你画完东西后立即创建一个图形,此时弹出窗口的大小似乎是固定的。
                            • 这是否意味着如果将 DPI 设置为 1,那么 figsize 将变为像素单位而不是英寸单位?这在 web 和 GUI 界面上使用 matplotlib 时会更有用。
                            • 使用 figsize(1,1) 你会在图像中得到 1:1 的比例吗?因为我所有的饼图都显示为椭圆形,而我发现使它们变圆的唯一方法是使用 plot.axis("equals")。它们会产生相同的效果还是表现不同?
                            • @BrenoBaiardi 这个问题是关于身材的。即使整个图形是 1:1,图形顶部的轴仍可能具有不相等的纵横比,即使轴框是 1:1,数据在 x 和 y 方向上的缩放比例也可能不同。所以,不,该命令不能保证相同的纵横比。
                            • 注意,如果你在figsize中设置的数字太大,图形只会最大化到屏幕边缘。这开启了水平最大化和垂直最大化的可能性。
                            【解决方案18】:
                            import matplotlib.pyplot as plt
                            plt.figure(figsize=(20,10))
                            plt.plot(x,y) ## This is your plot
                            plt.show()
                            

                            你也可以使用:

                            fig, ax = plt.subplots(figsize=(20, 10))
                            

                            【讨论】:

                              【解决方案19】:

                              您可以简单地使用(来自matplotlib.figure.Figure):

                              fig.set_size_inches(width,height)
                              

                              从 Matplotlib 2.0.0 开始,对画布的更改将立即可见,如 forward 关键字 defaults to True

                              如果你只想change the width or height而不是两者,你可以使用

                              fig.set_figwidth(val)fig.set_figheight(val)

                              这些也会立即更新您的画布,但仅限于 Matplotlib 2.2.0 及更高版本。

                              对于旧版本

                              您需要明确指定forward=True,以便在比上面指定的版本更早的版本中实时更新您的画布。请注意,set_figwidthset_figheight 函数在 Matplotlib 1.5.0 之前的版本中不支持 forward 参数。

                              【讨论】:

                                【解决方案20】:

                                弃用说明:
                                根据official Matplotlib guide,不再推荐使用pylab 模块。请考虑改用matplotlib.pyplot 模块,如this other answer 所述。

                                以下似乎有效:

                                from pylab import rcParams
                                rcParams['figure.figsize'] = 5, 10
                                

                                这使图形的宽度为 5 英寸,高度为 10 英寸

                                Figure 类然后将其用作其参数之一的默认值。

                                【讨论】:

                                • 这在 iPython notebook 的顶部也能很好地工作,它(给定 --pylab=inline)已经在顶层导入了 rcParams。
                                • 这在我的带有 OO 接口到 pyplot 和 Qt 后端的 Windows 机器上不起作用。 fig.set_size_inches(18.5, 10.5, forward=True) 工作。
                                • 这个答案目前在Meta进行讨论
                                • 对于 Python 版本:3.6.4,matplotlib:2.2.3 我认为您需要传递一个列表或元组,例如rcParams['figure.figsize'] = (5, 10)
                                • 任何人都知道为什么这在第一次运行单元格时不起作用?
                                【解决方案21】:

                                'matplotlib figure size' 在 Google 中的第一个链接是 AdjustingImageSize (Google cache of the page)。

                                这是来自上述页面的测试脚本。它会为同一张图片创建不同大小的test[1-3].png文件:

                                #!/usr/bin/env python
                                """
                                This is a small demo file that helps teach how to adjust figure sizes
                                for matplotlib
                                
                                """
                                
                                import matplotlib
                                print "using MPL version:", matplotlib.__version__
                                matplotlib.use("WXAgg") # do this before pylab so you don'tget the default back end.
                                
                                import pylab
                                import numpy as np
                                
                                # Generate and plot some simple data:
                                x = np.arange(0, 2*np.pi, 0.1)
                                y = np.sin(x)
                                
                                pylab.plot(x,y)
                                F = pylab.gcf()
                                
                                # Now check everything with the defaults:
                                DPI = F.get_dpi()
                                print "DPI:", DPI
                                DefaultSize = F.get_size_inches()
                                print "Default size in Inches", DefaultSize
                                print "Which should result in a %i x %i Image"%(DPI*DefaultSize[0], DPI*DefaultSize[1])
                                # the default is 100dpi for savefig:
                                F.savefig("test1.png")
                                # this gives me a 797 x 566 pixel image, which is about 100 DPI
                                
                                # Now make the image twice as big, while keeping the fonts and all the
                                # same size
                                F.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) )
                                Size = F.get_size_inches()
                                print "Size in Inches", Size
                                F.savefig("test2.png")
                                # this results in a 1595x1132 image
                                
                                # Now make the image twice as big, making all the fonts and lines
                                # bigger too.
                                
                                F.set_size_inches( DefaultSize )# resetthe size
                                Size = F.get_size_inches()
                                print "Size in Inches", Size
                                F.savefig("test3.png", dpi = (200)) # change the dpi
                                # this also results in a 1595x1132 image, but the fonts are larger.
                                

                                输出:

                                using MPL version: 0.98.1
                                DPI: 80
                                Default size in Inches [ 8.  6.]
                                Which should result in a 640 x 480 Image
                                Size in Inches [ 16.  12.]
                                Size in Inches [ 16.  12.]
                                

                                两个音符:

                                1. 模块cmets与实际输出不同。

                                2. This answer 可以轻松地将所有三个图像合并到一个图像文件中,以查看大小的差异。

                                【讨论】:

                                • 每次我试图回忆如何做到这一点时,我都会在这篇文章中结束。所以,这是我通常要寻找的代码:fig = plt.figure() default_size = fig.get_size_inches() fig.set_size_inches( (default_size[0]*2, default_size[1]*2) )
                                【解决方案22】:

                                由于 Matplotlib isn't able 原生使用公制,如果您想以厘米等合理的长度单位指定图形的大小,可以执行以下操作(代码来自 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)
                                

                                那么你可以使用:

                                plt.figure(figsize=cm2inch(21, 29.7))
                                

                                【讨论】:

                                  【解决方案23】:

                                  请尝试以下简单代码:

                                  from matplotlib import pyplot as plt
                                  plt.figure(figsize=(1,1))
                                  x = [1,2,3]
                                  plt.plot(x, x)
                                  plt.show()
                                  

                                  您需要在绘制之前设置图形大小。

                                  【讨论】:

                                  • 这个答案告诉我它是 matplotlib.pyplot.figure,其他人没有说清楚。我一直在尝试类似matplotlib.figurematplotlib.figure.Figure
                                  • "_tkinter.TclError: 没有足够的可用内存用于图像缓冲区"
                                  • plt.figure(figsize=(1,1)) 是关键。谢谢。
                                  • 在 jupyter notebook 中,这对我有用:plt.figure(figsize=(20,10))
                                  • 对于那些使用 jupyter notebook 的人,请确保在其他 plt 命令之前使用 plt.figure(figsize=(15, 10))。
                                  【解决方案24】:

                                  尝试注释掉fig = ... 这一行

                                  %matplotlib inline
                                  import numpy as np
                                  import matplotlib.pyplot as plt
                                  
                                  N = 50
                                  x = np.random.rand(N)
                                  y = np.random.rand(N)
                                  area = np.pi * (15 * np.random.rand(N))**2
                                  
                                  fig = plt.figure(figsize=(18, 18))
                                  plt.scatter(x, y, s=area, alpha=0.5)
                                  plt.show()
                                  

                                  【讨论】:

                                    猜你喜欢
                                    • 1970-01-01
                                    • 2020-03-11
                                    • 1970-01-01
                                    相关资源
                                    最近更新 更多