2

给定一些数据:

pt = pd.DataFrame({'alrmV':[000,000,000,101,101,111,111],
                   'he':[e,e,e,e,h,e,e],
                   'inc':[0,0,0,0,0,1,1]})

我想创建一个在行和列上分开的条形图。

g = sns.FacetGrid(pt, row='inc', col='he', margin_titles=True)
g.map( sns.barplot(pt['alrmV']), color='steelblue')

这行得通,但我还要如何添加:

  1. 有序的 x 轴
  2. 仅显示前两个按计数的alrmV类型

为了获得一个显示前 2 个计数类型的有序 x 轴,我尝试了这个分组,但无法将其放入 Facet 网格中:

grouped = pt.groupby( ['he','inc'] )
grw= grouped['alrmV'].value_counts().fillna(0.) #.unstack().fillna(0.)
grw[:2].plot(kind='bar')

使用 FacetGrid,切片限制了显示的总数

g.map(sns.barplot(pt['alrmV'][:10]), color='steelblue')

那么我怎样才能得到一个条形图,它在行和列上分开,并且是有序的并且只显示前 2 个计数?

4

1 回答 1

4

我无法让示例与您提供的数据一起使用,因此我将使用其中一个示例数据集来演示:

import seaborn as sns
tips = sns.load_dataset("tips")

我们将sex在列、smoker行中绘制一个图,day用作条形图的x变量。为了按顺序排列前两天,我们可以做

top_two_ordered = tips.day.value_counts().order().index[-2:]

然后您可以将此列表传递给 的x_order参数barplot

虽然你可以直接在这里使用,但使用该功能FacetGrid可能更容易:factorplot

g = sns.factorplot("day", col="sex", row="smoker",
               data=tips, margin_titles=True, size=3,
               x_order=top_two_ordered)

绘制:

在此处输入图像描述

虽然我不建议完全按照您的建议进行操作(在每个方面为不同的 x 值绘制条形图),但可以通过执行类似的操作来完成

g = sns.FacetGrid(tips, col="sex", row="smoker", sharex=False)

def ordered_barplot(data, **kws):
    x_order = data.day.value_counts().order().index[-2:]
    sns.barplot(data.day, x_order=x_order)

g.map_dataframe(ordered_barplot)

使

在此处输入图像描述

于 2014-04-23T18:11:46.703 回答