简体   繁体   English

编辑 Seaborn 散点图和计数图的图例标题和标签

[英]Edit legend title and labels of Seaborn scatterplot and countplot

I am using seaborn scatterplot and countplot on titanic dataset.我在 titanic 数据集上使用 seaborn 散点图和计数图。
Here is my code to draw scatter plot.这是我绘制散点图的代码。 I also tried to edit legend label.我还尝试编辑图例标签。

ax = seaborn.countplot(x='class', hue='who', data=titanic)
legend_handles, _ = ax.get_legend_handles_labels()
plt.show();

输出

To edit legend label, I did this.要编辑图例标签,我这样做了。 In this case, there is no legend title anymore.在这种情况下,不再有图例标题。 How can I rename this title from 'who' to 'who1'?如何将此标题从“who”重命名为“who1”?

ax = seaborn.countplot(x='class', hue='who', data=titanic)
legend_handles, _= ax.get_legend_handles_labels()
ax.legend(legend_handles, ['man1','woman1','child1'], bbox_to_anchor=(1,1))
plt.show()

输出2

I used the same method to edit legend labels on scatter plot and the result is different here.我用同样的方法编辑散点图上的图例标签,这里的结果不同。 It uses 'dead' as legend title and use 'survived' as first legend label.它使用“死亡”作为图例标题,并使用“幸存”作为第一个图例标签。

ax = seaborn.scatterplot(x='age', y='fare', data=titanic, hue = 'survived')
legend_handles, _= ax.get_legend_handles_labels()
ax.legend(legend_handles, ['dead', 'survived'],bbox_to_anchor=(1.26,1))
plt.show()

在此处输入图像描述

  1. Is there a parameter to delete and add legend title?是否有删除和添加图例标题的参数?

  2. I used same codes on two different graphs and outcome of legend is different.我在两个不同的图表上使用了相同的代码,图例的结果是不同的。 Why is that?这是为什么?

Try using尝试使用

ax.legend(legend_labels, ['man1','woman1','child1'], 
          bbox_to_anchor=(1,1), 
          title='whatever title you want to use')

With seaborn v0.11.2 or later, use the move_legend() function.对于 seaborn v0.11.2 或更高版本,使用move_legend()函数。

From the FAQs page :常见问题解答页面

With seaborn v0.11.2 or later, use the move_legend() function.对于 seaborn v0.11.2 或更高版本,使用 move_legend() 函数。

On older versions, a common pattern was to call ax.legend(loc=...) after plotting.在旧版本中,一种常见的模式是在绘图后调用 ax.legend(loc=...) 。 While this appears to move the legend, it actually replaces it with a new one, using any labeled artists that happen to be attached to the axes.虽然这似乎移动了图例,但它实际上用一个新的图例替换了图例,使用了恰好附加到轴上的任何带标签的艺术家。 This does not consistently work across plot types.这并不适用于各种绘图类型。 And it does not propagate the legend title or positioning tweaks that are used to format a multi-variable legend.而且它不会传播用于格式化多变量图例的图例标题或定位调整。

The move_legend() function is actually more powerful than its name suggests, and it can also be used to modify other legend parameters (font size, handle length, etc.) after plotting. move_legend()函数其实比它的名字更强大,它还可以用来在出图后修改其他图例参数(字体大小、句柄长度等)。

Why does the legend order sometimes differ?为什么图例顺序有时不同?

You can force the order of the legend via hue_order=['man', 'woman', 'child'] .您可以通过hue_order=['man', 'woman', 'child']强制图例的顺序。 By default, the order is either the order in which they appear in the dataframe (when the values are just strings), or the order imposed by pd.Categorical .默认情况下,顺序要么是它们在数据框中出现的顺序(当值只是字符串时),要么是pd.Categorical强加的顺序。

How to rename the legend entries如何重命名图例条目

The surest way is to rename the column values, eg最可靠的方法是重命名列值,例如

titanic["who"] = titanic["who"].map({'man': 'Man1', 'woman': 'Woman1', 'child': 'Child1'})

If the entries of the column exist of numbers in the range 0,1,... , you can use pd.Categorical.from_codes(...) .如果列的条目存在0,1,...范围内的数字,则可以使用pd.Categorical.from_codes(...) This also forces an order.这也强制执行命令。

Specific colors for specific hue values特定色调值的特定颜色

There are many options to specify the colors to be used (via palette= ).有许多选项可以指定要使用的颜色(通过palette= )。 To assign a specific color to a specific hue value, the palette can be a dictionary, eg要将特定颜色分配给特定色调值,调色板可以是字典,例如

palette = {'Man1': 'cornflowerblue', 'Woman1': 'fuchsia', 'Child1': 'limegreen'}

Renaming or removing the legend title重命名或删除图例标题

sns.move_legend(ax, title=..., loc='best') sets a new title. sns.move_legend(ax, title=..., loc='best')设置一个新标题。 Setting the title to an empty string removes it (this is useful when the entries are self-explaining).将标题设置为空字符串会将其删除(这在条目不言自明时很有用)。

A code example代码示例

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

titanic = sns.load_dataset('titanic')
# titanic['survived'] = titanic['survived'].map({0:'Dead', 1:'Survived'})
titanic['survived'] = pd.Categorical.from_codes(titanic['survived'], ['Dead', 'Survived'])
palette = {'Dead': 'navy', 'Survived': 'turquoise'}

ax = sns.scatterplot(data=titanic, x='age', y='fare', hue='survived', palette=palette)
sns.move_legend(ax, title='', loc='best')  # remove the title

plt.show()

带有重命名图例条目的 sns.scatterplot

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

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