繁体   English   中英

绘图:具有三列的堆栈条

[英]Plot: Stack bar with three columns

我有以下数据框。

df = '''type    time    gender
0   A   660.0   M
1   B   445.0   M
2   C   68.0    M
3   A   192.2   F
4   B   82.9    F
'''

我在数据上方使用以下代码图。

import matplotlib.ticker as mtick
import matplotlib.pyplot as plt

df.groupby(['gender','type']).count().groupby(level=0).apply(
    lambda x:100*x / x.sum()
).unstack().plot(kind='bar',stacked=True)

plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter())
plt.legend( prop={'size': 16})
plt.show()

我的输出:

在此处输入图片说明

问:我想绘制涉及数据时间的这两个条形图。 如果有人可以提供帮助,不胜感激!

使用matplotlib ,然后

(df.pivot_table(index='gender', columns='type', 
               values='time', aggfunc='sum', 
               fill_value=0)
   .apply(lambda x: x/x.sum(), axis=1)
   .plot.bar(stacked=True)
)

输出:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM