Python-based grouped histogram data

How to create a complex histogram: 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()

For grouped data.

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]})

Like df1.A.hist(by=df1.group, bins='doane', stacked=True)or

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

only leads to: enter image description here

+4
source share
1 answer

You can have pivotyour DataFrame so that each group is in a different column and then generates a histogram.

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

Edit: option added stacked=Truetohist()

+4
source

Source: https://habr.com/ru/post/1653547/


All Articles