【问题标题】:How to change the figure size of a seaborn axes or figure level plot如何更改 seaborn 轴或图形级别图的图形大小
【发布时间】:2020-05-24 22:25:30
【问题描述】:

如何更改图像的大小以使其适合打印?

例如,我想使用 A4 纸,横向尺寸为 11.7 英寸 x 8.27 英寸。

【问题讨论】:

    标签: python matplotlib seaborn figsize


    【解决方案1】:

    您还可以通过在 seaborn set 方法中使用键 'figure.figsize' 将字典传递给 rc 参数来设置图形大小:

    import seaborn as sns
    
    sns.set(rc={'figure.figsize':(11.7,8.27)})
    

    其他替代方法可能是使用rcParamsfigure.figsize 来设置图形大小如下:

    from matplotlib import rcParams
    
    # figure size in inches
    rcParams['figure.figsize'] = 11.7,8.27
    

    更多详情请见matplotlib documentation

    【讨论】:

    • 与其他解决方案不同,此解决方案不采用某种定义绘图的方式。谢谢。
    • 请注意,当您调用 sns.set() 时,它会将您的图形样式默认为 sns 默认值而不是 matplotlib 默认值,例如,您的图形会突然有一个带有白色网格的灰色背景 - 请参阅在这里:seaborn.pydata.org/tutorial/aesthetics.html。此外,这对我的情节(sns.pairplot)的大小没有任何影响。
    • 我的也不是 sns.boxplot
    • 感谢@Melissa。这让我意识到我必须在.set_style() 之前致电.set()
    • 唉,他们都没有在 Jupyter Lab 中产生任何情节。 fig, ax = pyplot.subplots(figsize=(20, 2)); a = sns.lineplot(ax=ax, x=..., y=...) 会按预期工作。当需要使用“技巧”设置这些参数时,我总是感到惊讶,因为这些参数在 seaborn 中应该很简单,因为它经常使用。
    【解决方案2】:

    您需要提前创建 matplotlib 的 Figure 和 Axes 对象,指定图形的大小:

    from matplotlib import pyplot
    import seaborn
    
    import mylib
    
    a4_dims = (11.7, 8.27)
    df = mylib.load_data()
    fig, ax = pyplot.subplots(figsize=a4_dims)
    seaborn.violinplot(ax=ax, data=df, **violin_options)
    

    【讨论】:

    • 这个解决方案似乎不适用于后面的代码(不同类型的情节)。有任何想法吗?我假设“mylib”只是一个存储数据的库,在此代码中不需要:` fig, ax = pyplot.subplots(figsize=(12,6)); sns.jointplot(memoryPrice['price'], memoryPrice['Memory']) `
    • 这个答案在@TMWP 的情况下不起作用,因为jointplot 是一种图形级别的方法。请参阅下面的答案。
    • 这个答案不适用于那些不接受 ax 作为输入的绘图类型,例如sns.lmplot()
    • seaborn 中的绘图大小应使用heightaspect 参数设置,如此处所述stackoverflow.com/a/51602446/2412831
    • @LeandroOrdonez 这并不真正适用于轴级功能。
    【解决方案3】:

    请注意,如果您尝试传递到 seaborn 中的“图形级别”方法(例如 lmplotcatplot / factorplotjointplot),您可以并且应该使用 @ 在参数中指定它987654328@和aspect

    sns.catplot(data=df, x='xvar', y='yvar', 
        hue='hue_bar', height=8.27, aspect=11.7/8.27)
    

    请参阅https://github.com/mwaskom/seaborn/issues/488Plotting with seaborn using the matplotlib object-oriented interface,了解有关图形级别方法不遵守轴规范的更多详细信息。

    【讨论】:

    • 这是迄今为止唯一正确处理不接受 ax 作为参数的 sns 图的答案。
    • 请注意,高度和纵横比控制单个“平面”的尺寸,即子图。所以这不会直接调整完整的图形尺寸。
    【解决方案4】:

    您可以将上下文设置为poster 或手动设置fig_size

    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    np.random.seed(0)
    n, p = 40, 8
    d = np.random.normal(0, 2, (n, p))
    d += np.log(np.arange(1, p + 1)) * -5 + 10
    
    
    # plot
    sns.set_style('ticks')
    fig, ax = plt.subplots()
    # the size of A4 paper
    fig.set_size_inches(11.7, 8.27)
    sns.violinplot(data=d, inner="points", ax=ax)    
    sns.despine()
    
    fig.savefig('example.png')
    

    【讨论】:

    • 这个答案不适用于那些不接受 ax 作为输入的绘图类型,例如sns.lmplot()
    • 为了扩展 Chris 的回答,一些 seaborn 绘图会生成具有多个轴的复合图形,因此它们不能将单个轴作为参数。
    • 这在尝试绘制小提琴图时对我有用。我能够在 Jupiter 实验室笔记本中更改内联图形的大小。
    【解决方案5】:

    先导入matplotlib,用它来设置图形的大小

    from matplotlib import pyplot as plt
    import seaborn as sns
    
    plt.figure(figsize=(15,8))
    ax = sns.barplot(x="Word", y="Frequency", data=boxdata)
    

    【讨论】:

      【解决方案6】:

      这可以使用:

      plt.figure(figsize=(15,8))
      sns.kdeplot(data,shade=True)
      

      【讨论】:

      • +1 -- 如果您不必import matplotlib.pyplot as plt 来使用这个对图形的简单调用,那就太好了。我想知道他们为什么不直接用sns.set_figure_size() 公开它。
      【解决方案7】:

      除了 elz 关于返回多图网格对象的“图形级别”方法的回答之外,还可以使用以下方法显式设置图形高度和宽度(即不使用纵横比)方法:

      import seaborn as sns 
      
      g = sns.catplot(data=df, x='xvar', y='yvar', hue='hue_bar')
      g.fig.set_figwidth(8.27)
      g.fig.set_figheight(11.7)
      

      【讨论】:

      • set_figwidthset_figheight 适用于网格对象。 >>> import seaborn >>> import matplotlib.pyplot as pyplot >>> Tips = seaborn.load_dataset("tips") >>> g = seaborn.FacetGrid(tips, col="time", row="smoker") >>> g = g.map(pyplot.hist, "total_bill") >>> g.fig.set_figwidth(10) >>> g.fig.set_figheight(10)
      • 也许 API 改变了,但对我来说是 g.figure.set_figwidth 而不是 g.fig.set_figwidth。我正在使用 matplotlib 3.1.0 版和 seaborn 0.9.0
      • 适用于 seaborn 版本 0.11.1 - 此页面上的其他解决方案无效
      • 非常感谢,这是唯一对我有用的解决方案。已经尝试了 15 分钟来解决这个问题
      【解决方案8】:

      这也应该有效。

      from matplotlib import pyplot as plt
      import seaborn as sns    
      
      plt.figure(figsize=(15,16))
      sns.countplot(data=yourdata, ...)
      

      【讨论】:

        【解决方案9】:

        对于我的情节(sns factorplot),建议的答案效果不佳。

        所以我使用

        plt.gcf().set_size_inches(11.7, 8.27)
        

        就在与 seaborn 的情节之后(因此无需将斧头传递给 seaborn 或更改 rc 设置)。

        【讨论】:

        • 这是唯一适用于我的 FacetGrid 解决方案 python g = sns.FacetGrid(df.set_index('category'), col="id") pyplot.gcf().set_size_inches(11.7, 8.27) g.map(lambda data, color: data.plot.barh(color=color), "count")
        • 这里也一样。似乎sns.FacetGrid 会根据计算值(由heightaspect 设置)设置图形大小,并在seaborn 绘图后直接更改图形大小。更改图形大小后可能会发生其他情节的微调
        【解决方案10】:
        # Sets the figure size temporarily but has to be set again the next plot
        plt.figure(figsize=(18,18))
        
        sns.barplot(x=housing.ocean_proximity, y=housing.median_house_value)
        plt.show()
        

        【讨论】:

          【解决方案11】:

          Paul H 和 J. Li 的最佳答案不适用于所有类型的 seaborn 人物。对于FacetGrid 类型(例如sns.lmplot()),使用sizeaspect 参数。

          Size 同时改变高度和宽度,保持纵横比。

          Aspect 只改变宽度,保持高度不变。

          你总是可以通过使用这两个参数来获得你想要的尺寸。

          信用:https://stackoverflow.com/a/28765059/3901029

          【讨论】:

            【解决方案12】:

            一些尝试过的方法:

            import seaborn as sns
            import matplotlib.pyplot as plt
            ax, fig = plt.subplots(figsize=[15,7])
            sns.boxplot(x="feature1", y="feature2",data=df) # where df would be your dataframe
            

            import seaborn as sns
            import matplotlib.pyplot as plt
            plt.figure(figsize=[15,7])
            sns.boxplot(x="feature1", y="feature2",data=df) # where df would be your dataframe
            

            【讨论】:

              【解决方案13】:
              • 调整绘图的大小取决于绘图是像seaborn.displot 这样的图形级绘图,还是像seaborn.histplot 这样的轴级绘图此答案适用于任何图形或坐标轴水平图
              • seabornmatplotlib 的高级 API,因此 seaborn 使用 matplotlib 方法
              • python 3.8.12matplotlib 3.4.3seaborn 0.11.2 中测试

              进口和数据

              import seaborn as sns
              import matplotlib.pyplot as plt
              
              # load data
              df = sns.load_dataset('penguins')
              

              sns.displot

              • 可以使用height 和/或aspect 参数调整图形级别图的大小
              • 另外,可以通过访问fig对象并使用.set_dpi()来设置图的dpi
              p = sns.displot(data=df, x='flipper_length_mm', stat='density', height=4, aspect=1.5)
              p.fig.set_dpi(100)
              
              • 没有p.fig.set_dpi(100)

              • p.fig.set_dpi(100)

              sns.histplot

              • 可以使用figsize 和/或dpi 调整坐标轴级别图的大小
              # create figure and axes
              fig, ax = plt.subplots(figsize=(6, 5), dpi=100)
              
              # plot to the existing fig, by using ax=ax
              p = sns.histplot(data=df, x='flipper_length_mm', stat='density', ax=ax)
              
              • 没有dpi=100

              • dpi=100

              【讨论】:

                猜你喜欢
                • 2021-11-11
                • 2018-12-26
                • 2014-11-27
                • 1970-01-01
                相关资源
                最近更新 更多