繁体   English   中英

删除Seaborn barplot图例标题

[英]Remove Seaborn barplot legend title

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

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

传说中有一个标题(性别),我想删除。

我怎么能实现这一目标?

这可能是一个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()

示例结果:

在此输入图像描述

一种不太常见的方法是使用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()

结果是 resulting_plot

您可以删除图例标题:

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

如果您希望图例显示在绘图轴之外,这是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')
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM