Seaborn:如何在catplot中设置自定义“hue”标签而不是自动标签

3
我正在使用seaborn创建漂亮的分类图。 seaborn.catplot 对我非常有帮助。 它使用 pandas.DataFrame 的列名作为标签,但有时我想在我的图表上重命名这些标签。
很明显,我可以使用matplotlib.pyplot来设置轴标签、标题等等。但是如何更改色调标签?我不想在我的图表上显示ugly_column_name。我想要一个不同的字符串,例如Pretty Category
这是我绘制的极其简化的图表代码和结果图像。我如何在这里编辑色调标签?是否有一个简单的一行代码?
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

data = pd.DataFrame({"ugly_column_name": ["foo", "foo", "foo", "bar", "bar", "bar"],
                     "x": [1, 2, 3, 1, 2, 3],
                     "y": [1, 1.1, 1.5, 1.1, 1.5, 2.0]}
                    )
sns.catplot(x="x", y="y", data=data, hue="ugly_column_name")
plt.xlabel('More than just lowerscore x')

catplot sample


重命名数据框中的列名。 - ImportanceOfBeingErnest
这不是解决问题的最佳方式。标签可能很长,可能包含特殊字符等。在绘图后我仍然需要使用数据框,并且不想将长标签作为列名键入。 - Dmitrii Begal
2个回答

0

已使用Seaborn 0.10.1进行测试

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

data = pd.DataFrame({"ugly_column_name": ["foo", "foo", "foo", "bar", "bar", "bar"],
                     "x": [1, 2, 3, 1, 2, 3],
                     "y": [1, 1.1, 1.5, 1.1, 1.5, 2.0]}
                    )
g = sns.catplot(x="x", y="y", data=data, hue="ugly_column_name")
plt.xlabel('More than just lowerscore x')

# Now change the hue (legend) title
g._legend.set_title('Pretty Category')

0

你可以使用Dataframe.replace

在你的情况下,将这行代码添加到你的程序中:

data = data.replace(to_replace="foo", value="foo_alternative")

请检查代码片段:
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

data = pd.DataFrame({"ugly_column_name": ["foo", "foo", "foo", "bar", "bar", "bar"],
                     "x": [1, 2, 3, 1, 2, 3],
                     "y": [1, 1.1, 1.5, 1.1, 1.5, 2.0]}
                    )

data = data.replace(to_replace="foo", value="foo_alternative")
data = data.replace(to_replace="bar", value="bar_alternative")

sns.catplot(x="x", y="y", data=data, hue="ugly_column_name")
plt.xlabel('More than just lowerscore x')

你误解了我的意思。我不需要将“foo”和“bar”字符串重命名,它们的名称很好,并且可以使用您的代码轻松更改。但是我想将“ugly_column_name”重命名为“Pretty name”。目前,我正在使用@ImportanceOfBeingErnest的解决方案,但我认为这不是最好的解决方案。 - Dmitrii Begal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接