Python 如何使用 seaborn 为我的 DataFrame 创建堆叠条形图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47138271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a stacked bar chart for my DataFrame using seaborn?
提问by Dinosaurius
I have a DataFrame df
:
我有一个数据帧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]])
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
.
我想创建一个堆积条形图,以便每个堆栈都对应,App
而 Y 轴将包含1
值的计数,而 X 轴将是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='Cou??nt')
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()
回答by Scott Boston
You could use pandas plot as @Bharath suggest:
您可以按照@Bharath 的建议使用熊猫图:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
输出:
Updated:
更新:
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))
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))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
更新的 Pandas 0.21.0+reindex_axis
已弃用,请使用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))
Output:
输出: