使用 seaborn barplot 绘制宽格式数据帧

Using seaborn barplot to plot wide-form dataframes

我正在尝试制作一个条形图,其中包含我 DataFrame 中的所有观察结果,它看起来像这样:Dataframe(行 = 年,列 = 对象,值 = 违反对象年)

我在使用默认 pandas 时得到了正确类型的图表 plot:

cluster_yearly_results_df.plot.bar()

Correct Bar Plot

但是,我想使用 seaborn,我在输入宽格式数据帧时遇到问题,使用:

sns.barplot(data=cluster_yearly_results_df)

我可以使用 seaborn 做我想做的事吗?

seaborn.barplot 文档说:

A bar plot represents an estimate of central tendency for a numeric variable with the height of each rectangle and provides some indication of the uncertainty around that estimate using error bars.

换句话说,目的是用代表 mean 的单个条和代表 std 的误差条来表示单个变量的多个值。您希望像 pandas.plot.bar() 那样用条形图表示单个值。

话虽如此,您可以如下调整 DataFrame 以匹配 seaborn 界面。以与您相似的 DataFrame 开头:

df = pd.DataFrame(np.random.randint(low=0, high=10, size=(10, 3)), columns=list('ABC'))

   A  B  C
0  7  6  4
1  3  5  9
2  3  0  5
3  0  1  3
4  9  7  7

使用 .stack().reset_index() 创建两个列来唯一标识 y 中的每个值:

df = df.stack().reset_index()
df.columns = ['x', 'hue', 'y']

产生:

   x hue  y
0  0   A  6
1  0   B  1
2  0   C  2
3  1   A  5
4  1   B  7

然后剧情:

sns.barplot(y='y', x='x', hue='hue', data=df)