【问题标题】:How to make a stacked bar chart in matplotlib?如何在 matplotlib 中制作堆积条形图?
【发布时间】:2021-03-24 13:14:33
【问题描述】:

这是我正在使用的一些代码:(数据是组成的)

# create dataset
mydf = {'Person': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'],
        'Punctuality':  ['On Time', 'Late', 'On Time', 'Early', 'On Time', 'Early',
                     'Late', 'Early', 'Early', 'On Time', 'On Time', 'Late'],
        'Diverted': [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1]
       }
# note: in 'Diverted', 1 = True, 0 = False

mydf = pd.DataFrame (mydf, columns = ['Person', 'Punctuality', 'Diverted'], index = list(range(0,12)))
mydf
# create freq table
mydf_p = (pd.DataFrame(mydf['Punctuality'].value_counts())).reset_index()
mydf_p.rename(columns={ mydf_p.columns[0]: "Punctuality", mydf_p.columns[1]: "Frequency" }, inplace = True)
mydf_p
# create bar chart
plot = plt.subplots(nrows=1, ncols=1, figsize=(4, 5))
fig, (ax) = plot
x = mydf_p['Punctuality'].to_list()
y = mydf_p['Frequency'].to_list()

ax.bar(x, y, color='cornflowerblue')
ax.set_ylabel('Frequency')
ax.set_xlabel('Punctuality')

我如何使用这些数据制作堆叠条形图,其中准时条按人们的旅程是否被改道的比例分开??

我尝试按照文档进行操作,但我仍然对如何执行此操作感到困惑。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.bar.html

真的希望有人能帮忙:)

【问题讨论】:

    标签: python pandas matplotlib graph bar-chart


    【解决方案1】:

    你的问题不是很清楚。也许预期的输出会有所帮助。如果我猜对了,请尝试 groupby、unstack 和 plot。

    mydf.groupby(['Punctuality','Diverted']).Person.count().unstack().plot.bar(stacked=True)
    

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 2019-11-28
      • 2018-03-10
      • 2018-11-26
      • 2021-07-10
      • 1970-01-01
      • 2021-02-27
      • 2020-09-28
      • 1970-01-01
      相关资源
      最近更新 更多