Python堆积直方图分组数据

时间:2016-09-03 19:22:05

标签: python pandas plot visualization

如何创建像这样的堆叠直方图: enter image description here

import numpy as np
import pylab as P
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')

%pylab inline
pylab.rcParams['figure.figsize'] = (15, 4)
mu, sigma = 200, 25
x = mu + sigma*P.randn(1000,2)
n, bins, patches = P.hist(x, 10, normed=1, histtype='bar', stacked=True)
P.show()

对于分组数据。

import pandas as pd
df1 = pd.DataFrame({'A': [1,2,3,4,5,6,7,8,9],'group': [1,0,0,0,0,1,1,1,1]})

作为 df1.A.hist(by=df1.group, bins='doane', stacked=True)

df1.A.hist(by=df1.group, bins='doane')

只会导致: enter image description here

1 个答案:

答案 0 :(得分:4)

您可以pivot您的DataFrame,以便每个组位于不同的列中,然后生成直方图。

df1 = pd.DataFrame({'A': [1,2,3,4,5,6,7,8,9],'group': [1,0,0,0,0,1,1,1,1]})
df1.pivot(columns='group', values='A').plot.hist(stacked=True)

enter image description here

修改:将stacked=True参数添加到hist()