如何聚合数据时如何绘制堆积条形图

时间:2018-02-13 07:39:49

标签: python pandas matplotlib

我的数据框如下所示。 我想绘制类似堆积条形图的东西,其中堆栈的每一层都是列表邻域计数。事实上,我已经汇总了每个列表的计数。

enter image description here

enter image description here

我想要上面的内容

但是每种颜色的图表大小应该不同,y轴应该是计数。 我的代码:

df.groupby(['country','listing_neighborhood']).size().unstack().plot(kind='bar', stacked=True)

我也尝试过:

df.plot(x='country',y='count',stacked=True,kind='bar')

但我希望它们堆叠但似乎无法正常工作

enter image description here

3 个答案:

答案 0 :(得分:2)

我认为你需要pivot

df.pivot('country','listing_neighborhood','count').plot(stacked=True, kind='bar')

graph

答案 1 :(得分:1)

您可以通过绘制条形图来完成此操作,这些条形图等于它堆叠在其上的组的总和:

import matplotlib.pyplot as plt

def plot_bars(lst, colors, ax, position, width):
    for i in range(len(lst), 0, -1):
        # plot a bunch of rectangles on top of each other
        # each rectangle is equal to to the cumulative including that block
        rects1 = ax.bar(position, sum(lst[:i]), width, color=colors[i%len(lst)])

AR = [250, 218, 108]
AU = [90, 86, 38]
colors = ['r', 'g', 'b']

fig, ax = plt.subplots()

plot_bars(AR, colors, ax, 1, 0.5)
plot_bars(AU, colors, ax, 2, 0.5)

plt.show()

答案 2 :(得分:1)

你想要像this这样的东西吗?

import pandas as pd
import numpy as np
df = pd.DataFrame({"country":["AR","AR","AR","AU","AU","AU"],
                   "listing_neighborhood":["-unknown-","Copacabana","Ipanema","-unknown-","Copacabana","Ipanema"],
                   "count":[250,218,108,90,86,38]})
pt = pd.pivot_table(df, values="count", index="country", columns="listing_neighborhood", aggfunc=np.sum)
pt.plot.bar(stacked=True)