我有使用sns.countplot和图例使用“ hue”参数生成的图。我想在图例上显示“类别”计数的频率以及“ Cross_Tab”标签:
dfData:
Category Cross_Tab
Apple Yes
Apple No
Peach Yes
Peach No
Dog Yes
Dog Yes
图:
fig = sns.countplot(x="Category", hue="Cross_Tab", data=dfData, order=dfData.Category.value_counts().index)
传奇:
fig.legend(title="This is the Legend", loc='upper right')
这仅显示图例类别:
"This is the Legend"
Yes
No
所需的输出: 情节的图例应如下所示:
"This is the Legend"
Yes (n = 4)
No (n = 2)
查看了各种来源后,我了解到了这一点,但是它不起作用:
x = dfData.Cross_Tab.value_counts()
fig.legend("n=(%s)"%(x, ), title="This is the Legend", loc='upper right')
答案 0 :(得分:1)
您必须分别重新创建每个标签。
类似这样的东西似乎获得了期望的输出:
plt.figure()
ax = sns.countplot(x="Category", hue="Cross_Tab", data=df, order=df.Category.value_counts().index)
h, l = ax.get_legend_handles_labels()
counts = df.Cross_Tab.value_counts().reindex(l)
l = [f'{yn} (n={c})' for yn,c in counts.iteritems()]
ax.legend(h,l, title="This is the legend")