【问题标题】:Remove Seaborn barplot legend title删除 Seaborn 条形图图例标题
【发布时间】:2017-08-26 08:39:12
【问题描述】:

我使用 seaborn 绘制分组条形图,如 https://seaborn.pydata.org/examples/factorplot_bars.html

给我: https://seaborn.pydata.org/_images/factorplot_bars.png

我想删除图例上的标题(性别)。

我怎样才能做到这一点?

【问题讨论】:

  • 您需要添加您正在使用的代码。

标签: python matplotlib bar-chart seaborn


【解决方案1】:

您可以使用以下方法删除图例标题:

plt.gca().legend().set_title('')

【讨论】:

  • 在OOP界面怎么样?
  • 这应该是答案。它的工作原理和最少的假设和代码。
  • 对我不起作用。
【解决方案2】:

这可能是一个 hacky 解决方案,但它有效:如果您告诉 Seaborn 在绘图时将其关闭,然后将其添加回来,则它没有图例标题:

g = sns.factorplot(x='Age Group',y='ED',hue='Became Member',col='Coverage Type',
                   col_wrap=3,data=gdf,kind='bar',ci=None,legend=False,palette='muted')
#                                                         ^^^^^^^^^^^^
plt.suptitle('ED Visit Rate per 1,000 Members per Year',size=16)
plt.legend(loc='best')
plt.subplots_adjust(top=.925)
plt.show()

示例结果:

【讨论】:

    【解决方案3】:

    一个不那么老套的方法是使用 matplotlib 的面向对象接口。通过获得对坐标轴的控制,自定义绘图将变得更加容易。

    import seaborn as sns
    import matplotlib.pyplot as plt
    sns.set(style="whitegrid")
    
    # Load the example Titanic dataset
    titanic = sns.load_dataset("titanic")
    
    # Draw a nested barplot to show survival for class and sex
    fig, ax = plt.subplots()
    g = sns.factorplot(x="class", y="survived", hue="sex", data=titanic,
                       size=6, kind="bar", palette="muted", ax=ax)
    sns.despine(ax=ax, left=True)
    ax.set_ylabel("survival probability")
    l = ax.legend()
    l.set_title('Whatever you want')
    fig.show()
    

    结果

    【讨论】:

    • 不幸的是,这不适用于 seaborn.lineplot (v0.9.0)。
    【解决方案4】:

    如果您希望图例显示在绘图轴之外,这是factorplot 的默认设置,您可以使用FacetGrid.add_legendfactorplot 返回一个FacetGrid 实例)。其他方法允许您一次调整FacetGrid 中每个轴的标签

    import seaborn as sns
    import matplotlib.pyplot as plt
    sns.set(style="whitegrid")
    
    # Load the example Titanic dataset
    titanic = sns.load_dataset("titanic")
    
    # Draw a nested barplot to show survival for class and sex
    g = sns.factorplot(x="class", y="survived", hue="sex", data=titanic,
                       size=6, kind="bar", palette="muted", legend=False)
    (g.despine(left=True)
      .set_ylabels('survival probability')
      .add_legend(title='Whatever you want')
    )
    

    【讨论】:

      猜你喜欢
      • 2019-01-05
      • 2020-05-30
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-25
      相关资源
      最近更新 更多