用于分类数据的seaborn条形图,已分组 [英] seaborn bar chart for categorical data, grouped

查看:500
本文介绍了用于分类数据的seaborn条形图,已分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制按类别分组的分类数据条形图.

I would like to plot a bar chart of categorical data, grouped by series.

例如我有说6列的数据,下面用任意值填充

E.g. i have data with say 6 columns, here below filled with arbitrary values:

df = pd.DataFrame(np.arange(12).reshape(2,6),columns = ['A','B','C','D','E','F'] )

df = pd.DataFrame(np.arange(12).reshape(2,6),columns=['A','B','C','D','E','F'])

   A  B  C  D   E   F
0  0  1  2  3   4   5
1  6  7  8  9  10  11

,我想简单地将此简单信息绘制为条形图,其中对于每个列名AF,对于行0,将显示一个条形(其名称在轴或内联上),对于行1,每个具有其高度的条形都是该行和列的矩阵主体中的数字.

and I would like to simply plot this simple information as a bar chart where for each of the column names A-F, there will show one bar (with its name on the axis or inline) for row 0 and one bar for row 1, each bar having it's height being the number in the body of the matrix for that row and column.

与普通的分组条形图一样,行0的所有条形应与行1的所有条形不同.简而言之,仅是按两行分组的类别A-F的直方图.

Like normal grouped bar charts, all bars for row 0 should be a different color than those for row 1. Simply put, just a histogram for the categories A-F grouped by the two rows.

实际上,在我的真实数据中,每一行都具有真实名称,而不仅仅是索引号,在这里,两行都是01.

Actually in my real data each row has a real name instead of just an index number which is here 0 and 1 for the two rows.

到目前为止,我还没有找到通过Seaborn完成此任务的方法,只看到了一些关于matplotlib本身的可怕骇客.最简单的方法是什么?

I've found no way so far to get this done with seaborn, and only saw some terrible hacks with matplotlib itself. What is the simplest way to accomplish this?

有办法吗?

推荐答案

您可以绘制转置的数据框,如df.T.plot.bar().

You may plot the transposed dataframe like df.T.plot.bar().

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(np.arange(12).reshape(2,6),columns=list("ABCDEF"))

df.T.plot.bar()

plt.show()

使用seaborn需要重塑(融化")数据框:

Using seaborn this requires to reshape ("melt") the dataframe:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame(np.arange(12).reshape(2,6),columns=list("ABCDEF"))

df2 = pd.melt(df.reset_index(), id_vars=["index"], value_vars=df.columns)

sns.barplot(data=df2, x="variable", y="value", hue="index")

plt.show()

这篇关于用于分类数据的seaborn条形图,已分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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