python - Stacked bar plot by grouped data with pandas -


let's assume have pandas dataframe has many features , interested in two. i'll call them feature1 , feature2.

feature1 can have 3 possible values. feature2 can have 2 possible values.

i need bar plot grouped feature1 , stacked count of rows each value of feature2. (so there 3 stacks each 2 bars).

how achieve this?

at moment have

import pandas pd df = pd.read_csv('data.csv') df['feature1'][df['feature2'] == 0].value_counts().plot(kind='bar',label='0') df['feature1'][df['feature2'] == 1].value_counts().plot(kind='bar',label='1') 

but not want because doesn't stack them.

im not sure how in matplotlib (pandas default plotting library), if willing try different plotting library, quite easy bokeh.

here example

import pandas pd bokeh.charts import bar, output_file, show x = pd.dataframe({"gender": ["m","f","m","f","m","f"],                   "enrolments": [500,20,100,342,54,47],                   "class": ["comp-sci", "comp-sci",                             "psych", "psych",                             "history", "history"]})  bar = bar(x, values='enrolments', label='class', stack='gender',          title="number of students enrolled per class",          legend='top_right',bar_width=1.0) output_file("myplot.html") show(bar) 

stacked bar plot


Comments

Popular posts from this blog

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

python - How do I create a list index that loops through integers in another list -

c# - “System.Security.Cryptography.CryptographicException: Keyset does not exist” when reading private key from remote machine -