如何使用Seaborn为我的DataFrame创建堆积的条形图? [英] How to create a stacked bar chart for my DataFrame using seaborn?
问题描述
我有一个DataFrame df
:
I have a DataFrame df
:
df = pd.DataFrame(columns=["App","Feature1", "Feature2","Feature3",
"Feature4","Feature5",
"Feature6","Feature7","Feature8"],
data=[["SHA",0,0,1,1,1,0,1,0],
["LHA",1,0,1,1,0,1,1,0],
["DRA",0,0,0,0,0,0,1,0],
["FRA",1,0,1,1,1,0,1,1],
["BRU",0,0,1,0,1,0,0,0],
["PAR",0,1,1,1,1,0,1,0],
["AER",0,0,1,1,0,1,1,0],
["SHE",0,0,0,1,0,0,1,0]])
我想创建一个堆叠的条形图,以便每个堆叠对应于App
,而Y轴包含1
值的计数,而X轴为Feature
.
I want to create a stacked bar chart so that each stack would correspond to App
while the Y axis would contain the count of 1
values and the X axis would be Feature
.
它应该类似于此条形图,唯一的区别是现在我要查看堆栈条和带有颜色的图例:
It should be similar to this bar chart with the only difference that now I want to see stack bars and a legend with colors:
df_c = df.iloc[:, 1:].eq(1).sum().rename_axis('Feature').reset_index(name='Count')
df_c = df_c.sort_values('Count')
plt.figure(figsize=(12,8))
ax = sns.barplot(x="Feature", y="Count", data=df_c, palette=sns.color_palette("GnBu", 10))
plt.xticks(rotation='vertical')
ax.grid(b=True, which='major', color='#d3d3d3', linewidth=1.0)
ax.grid(b=True, which='minor', color='#d3d3d3', linewidth=0.5)
plt.show()
推荐答案
您可以使用@Bharath建议的熊猫图:
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
输出:
已更新:
导入ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index,axis = 1)\
.T.plot(kind ='bar',stack = True,
colormap = ListedColormap(sns.color_palette("GnBu",10)),
figsize =(12,6))
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
不建议使用更新的熊猫0.21.0+ reindex_axis
,请使用reindex
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
输出:
这篇关于如何使用Seaborn为我的DataFrame创建堆积的条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!