如何在使用“融化"分组的海洋计数图上的条形上方获取值. [英] How to get values above the bars on a seaborn countplot grouped using "melt"

查看:84
本文介绍了如何在使用“融化"分组的海洋计数图上的条形上方获取值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不可思议的计数图,但是我需要色带而不是色带来代替每个色带.我的输入是熊猫数据框.

I have a seaborn count plot, but instead of colour bars I need the value above each bar. My input is pandas data frame.

ax = sns.countplot(x="variable", hue="value", data=pd.melt(dfs))

这里dfs在不同的列上有很多条目.

here dfs has many entries for different columns.

例如,在蓝色条上方是男人",在棕色条上方是女人",在绿色条上方是孩子",而不是颜色说明.

For example, here "man" above the blue bar, "woman" above the brown bar and "child" above the green bar instead of the colour description.

推荐答案

有时候,不尝试找到调整seaborn的方法,而是直接使用matplotlib并从头开始构建图表,会更容易.

Sometimes it's easier to not try to find ways to tweak seaborn, but rather to directly use matplotlib and build a chart up from scratch.

在这里,我们可以假设有一个名为counts的数据框,看起来像

Here, we can assume to have a dataframe named counts that looks like

hue     c    m    w
class              
A      20   31   29
B      40  112   63
C      85  203  117

其中索引是沿x轴的位置,列是不同的色调.在下文中,groupedbarplot是一种函数,用于将此类数据框作为输入,并将条形图绘制为组,此外,还为每个条形图添加标签.

where the index are the positions along x axis and the columns are the different hues. In the following, groupedbarplot is a function to take such dataframe as input and plot the bars as groups, and in addition add a label to each one of them.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(42)

def groupedbarplot(df, width=0.8, annotate="values", ax=None, **kw):
    ax = ax or plt.gca()
    n = len(df.columns)
    w = 1./n
    pos = (np.linspace(w/2., 1-w/2., n)-0.5)*width
    w *= width
    bars = []
    for col, x in zip(df.columns, pos):
        bars.append(ax.bar(np.arange(len(df))+x, df[col].values, width=w, **kw))
        for val, xi in zip(df[col].values, np.arange(len(df))+x):
            if annotate:
                txt = val if annotate == "values" else col
                ax.annotate(txt, xy=(xi, val), xytext=(0,2), 
                            textcoords="offset points",
                            ha="center", va="bottom")
    ax.set_xticks(np.arange(len(df)))
    ax.set_xticklabels(df.index)
    return bars


df = pd.DataFrame({"class" : np.random.choice(list("ABC"), size=700, p=[.1,.3,.6]),
                   "hue" : np.random.choice(["m", "w" ,"c"], size=700, p=[.5,.3,.2])})

counts = df.groupby(["class", "hue"]).size().unstack()

groupedbarplot(counts, annotate="col")
plt.show()

我们也可以直接标记值,groupedbarplot(counts, annotate="values")

We could also label the values directly, groupedbarplot(counts, annotate="values")

这篇关于如何在使用“融化"分组的海洋计数图上的条形上方获取值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆