【问题标题】:Python seaborn / matplotlib - show frequency in legend categories in sns.countplot()Python seaborn / matplotlib - 在 sns.countplot() 的图例类别中显示频率
【发布时间】:2019-07-01 16:22:30
【问题描述】:

我使用 sns.countplot 生成的绘图带有使用“hue”参数的图例。我想在图例中显示“类别”计数的频率,以及“Cross_Tab”标签:

df数据:

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') 

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案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")
    

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 1970-01-01
      • 2023-04-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      相关资源
      最近更新 更多