Din*_*ius 18 python matplotlib pandas seaborn
我有一个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]])
Run Code Online (Sandbox Code Playgroud)
我想创建一个堆积条形图,以便每个堆栈对应于AppY轴将包含1值的计数和X轴Feature.
它应该类似于这个条形图,唯一的区别是现在我想看到堆栈条和带颜色的图例:
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()
Run Code Online (Sandbox Code Playgroud)
Sco*_*ton 42
您可以使用pandas plot作为@Bharath建议:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Run Code Online (Sandbox Code Playgroud)
输出:
更新:
来自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))
reindex_axis已弃用更新后的Pandas 0.21.0+ ,请使用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))
Run Code Online (Sandbox Code Playgroud)
输出:
| 归档时间: |
|
| 查看次数: |
47484 次 |
| 最近记录: |