gpt4 book ai didi

Python堆叠直方图分组数据

转载 作者:太空狗 更新时间:2023-10-30 02:56:49 24 4
gpt4 key购买 nike

如何创建这样的堆叠直方图: 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

最佳答案

您可以 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()

关于Python堆叠直方图分组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39310559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com