【问题标题】:How to get values above the bars on a seaborn countplot grouped using "melt"如何在使用“melt”分组的 seaborn 计数图上获得高于条形的值
【发布时间】:2019-04-02 13:59:23
【问题描述】:

我有一个 seaborn 计数图,但我需要每个条上方的值而不是彩条。我的输入是熊猫数据框。

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

这里 dfs 有许多不同列的条目。

例如,此处蓝色条上方为“man”,棕色条上方为“woman”,绿色条上方为“child”,而不是颜色描述。

【问题讨论】:

  • A、B、.. 以不同的列出现。在这里,我在 X 轴上有不同的组。因此,注释输入格式并没有帮助。谢谢。
  • 您应该仍然可以使用相同的注释功能,只需根据您的情况进行修改即可。例如,this page 讨论在melt 中维护一个索引,然后您可以将其传递给annotate,或者您可以手动传递一个标签列表
  • 我无法根据值而不是变量获取熔体 ID。我认为这是一个非常复杂的事情,因为基于色调的阴影也很困难,因为在我的要求中,我有不同的变量组,例如图中的“二等”有 4 个“谁”值。

标签: python pandas plot visualization seaborn


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2021-10-06
    • 2021-02-06
    • 2019-09-05
    • 1970-01-01
    相关资源
    最近更新 更多