[英]Changing legend labels on seaborn FacetGrid with barplot and boxplot?
How can you change the legend labels on a seaborn FacetGrid using barplots and boxplots?如何使用条形图和箱线图更改 seaborn FacetGrid 上的图例标签?
With scatterplots, you can do this easily:使用散点图,您可以轻松做到这一点:
tips = sns.load_dataset('tips')
g = sns.FacetGrid(data=tips, col='time')
g.map_dataframe(sns.scatterplot, x='total_bill', y='tip', hue='sex')
plt.legend(labels=['Men', 'Women'])
However, the same code using boxplots removes the color patches from the legend:但是,使用箱线图的相同代码会从图例中删除色块:
g = sns.FacetGrid(data=tips, col='time')
g.map_dataframe(sns.boxplot, x='smoker', y='tip', hue='sex')
plt.legend(labels=['Men', 'Women'])
Unlike barplot itself, the FacetGrid has no legend_
property, so existing solutions for barplots like this don't easily apply.与 barplot 本身不同,FacetGrid 没有
legend_
属性,因此此类条形图的现有解决方案不容易应用。
How do you modify the legend labels without removing the color patches?如何在不删除色块的情况下修改图例标签?
You can do this with FacetGrid's add_legend
method.您可以使用 FacetGrid 的
add_legend
方法来做到这一点。 When calling add_legend
, the legend_data
parameter maps labels to color patches.调用
add_legend
时, legend_data
参数将标签映射到色块。 FacetGrid stores its default legend data in a _legend_data
property. FacetGrid 将其默认图例数据存储在
_legend_data
属性中。 So all you need to do is pass a legend_data
parameter with your desired labels as the keys and the FacetGrid's default _legend_data
values as the values.因此,您需要做的就是传递一个
legend_data
参数,其中您需要的标签作为键,FacetGrid 的默认_legend_data
值作为值。
g = sns.FacetGrid(data=tips, col='time')
g.map_dataframe(sns.barplot, x='smoker', y='tip', hue='sex')
hue_labels = ['Men', 'Women']
g.add_legend(legend_data={
key: value for key, value in zip(hue_labels, g._legend_data.values())
})
g = sns.FacetGrid(data=tips, col='time')
g.map_dataframe(sns.boxplot, x='smoker', y='tip', hue='sex')
hue_labels = ['Men', 'Women']
g.add_legend(legend_data={
key: value for key, value in zip(hue_labels, g._legend_data.values())
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.