【问题标题】:Plot: Stack bar with three columns绘图:具有三列的堆栈栏
【发布时间】:2020-03-13 02:57:45
【问题描述】:

我有以下数据框。

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()

我的输出:

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

【问题讨论】:

  • involving the time of the data 是什么意思?您想要y 轴上的实际时间吗?
  • 是的。我想用实际时间绘制条形

标签: python pandas charts bar-chart


【解决方案1】:

使用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)
)

输出:

【讨论】:

  • 感谢您的回答。如何将 y 轴缩放 100%?
  • scale y-axis 100 是什么意思?这不再是你的实际时间了,是吗?
  • 实际时间。例如:F 只有 A 和 B 类型。但我想以 100 比例显示实际时间的比率。我很抱歉我的解释
  • 啊,我明白了。已更新。
  • 谢谢!这就是我想要但无法实现的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多