python - Seaborn 条形图图例标签失去颜色

标签 python matplotlib seaborn

我有一个 seaborn boxplot,当我尝试使用 plt.legend("Strings") 更改标签名称时,它会丢失标签的颜色。我需要在保持颜色编码的同时更改标签,但在搜索答案后我不知道如何执行此操作。
色调图例 1-4 对应于 1 = 对政治非常感兴趣到 4 = 完全不感兴趣。我想将图例色调标签从 1-4 更改为他们对政治的兴趣程度。
我的代码是:
套餐

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
我不知道如何以更简单的方式创建数据框,所以我这样做了
a1 = {'Reads Newspapers': 0, 'Interest in Politics': 1}
a2 = {'Reads Newspapers': 0, 'Interest in Politics': 2}
a3 = {'Reads Newspapers': 0, 'Interest in Politics': 3}
a4 = {'Reads Newspapers': 0, 'Interest in Politics': 4}
b1 = {'Reads Newspapers': 1, 'Interest in Politics': 1}
b2 = {'Reads Newspapers': 1, 'Interest in Politics': 2}
b3 = {'Reads Newspapers': 1, 'Interest in Politics': 3}
b4 = {'Reads Newspapers': 1, 'Interest in Politics': 4}

df1 = pd.DataFrame(data=a1, index=range(1))
df1 = pd.concat([df1]*23)
df2 = pd.DataFrame(data=a2, index=range(1))
df2 = pd.concat([df2]*98)
df3 = pd.DataFrame(data=a3, index=range(1))
df3 = pd.concat([df3]*99)
df4 = pd.DataFrame(data=a4, index=range(1))
df4 = pd.concat([df4]*18)
b1 = pd.DataFrame(data=b1, index=range(1))
b1 = pd.concat([b1]*468)
b2 = pd.DataFrame(data=b2, index=range(1))
b2 = pd.concat([b2]*899)
b3 = pd.DataFrame(data=b3, index=range(1))
b3 = pd.concat([b3]*413)
b4 = pd.DataFrame(data=b4, index=range(1))
b4 = pd.concat([b4]*46)
data = pd.concat([df1,df2,df3,df4,b1,b2,b3,b4])
产生错误的实际绘图
plt.figure(figsize=(10,8))
g = sns.barplot(data=data, x='Reads Newspapers', estimator=len,y='Interest in Politics', hue='Interest in Politics' )
plt.ylabel("Sample Size")
ax = plt.subplot()
ax = ax.set_xticklabels(["No","Yes"])

#plt.legend(["very interested","somewhat interested", "only a little interested", "not at all interested "],)
#plt.savefig('Newspaper policy')
Seaborn Boxplot about interest in politics
我尝试使用 plt.legend但是当我这样做时,图例标签会失去颜色,所以它变成了没有颜色关联的字符串,使它比以前更糟。
我现在已经编辑了我的整个脚本。
https://github.com/HenrikMorpheus/Newspaper-reading-survey/blob/master/politicalinterest.ipynb
由于某种我不知道的原因,它加载了一个错误,但您应该能够在 jupyter 中打开笔记本。

最佳答案

使用专用数据框列

一个选项是在数据框中创建一个带有相应标签的新列,并将此列用作 hue 的输入。 ,以便自动创建所需的标签。

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


df = pd.DataFrame({"reads" : ["Yes"] * 250 + ["No"]*150,
                  "interest" : [4,2,2,2,2,3,3,1,1,1]*40})

labels=["very interested","somewhat interested", 
        "only a little interested", "not at all interested"]
# Create new dataframe column with the labels instead of numbers
df["Interested in politics"] = df["interest"].map(dict(zip(range(1,5), labels)))

plt.figure(figsize=(10,8))
# Use newly created dataframe column as hue
ax = sns.barplot(data=df, x='reads', estimator=len,y='interest', 
                 hue='Interested in politics', hue_order=labels)
ax.set_ylabel("Sample Size")

plt.show()

enter image description here

手动设置标签。

您可以通过 ax.get_legend_handles_labels() 获取图例的句柄和标签。并使用它们用列表中的标签创建一个新的图例。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({"reads" : ["Yes"] * 250 + ["No"]*150,
                  "interest" : [4,2,2,2,2,3,3,1,1,1]*40})

labels=["very interested","somewhat interested", 
        "only a little interested", "not at all interested"]

plt.figure(figsize=(10,8))
ax = sns.barplot(data=df, x='reads', estimator=len,y='interest', hue='interest' )
ax.set_ylabel("Sample Size")

h, l = ax.get_legend_handles_labels()
ax.legend(h, labels, title="Interested in politics")
plt.show()

enter image description here

关于python - Seaborn 条形图图例标签失去颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53734332/

相关文章:

python - 极坐标/径向图上的刻度标签填充和刻度标签位置 - matplotlib

python - 如何使用 sharex=True 在 catplot(kind ='count')之上绘制 seaborn catplot(kind ='violin')

python - 使用类解决光之谜,但翻转困难。 (Python 3)

python - 如何标准化矩阵?

python - 用停止填充 pandas 系列中的 NA 值

python - Flask CLI 显示 "TypeError: exceptions must derive from BaseException"

python - pyplot twinx() 刻度重叠

python - 通过 txt 文件中的坐标进行粒子跟踪

python - 向 matplotlib/seaborn 图中的某些单元格添加自定义边框

python - 使用 seaborn 的盒须图不显示盒须