5

I could get the size info using groupby and add text to the corresponding location. But I can't help thinking there's a better way as this really seems mundane, something many people would like to see...

To illustrate, the following code would generate a grouped boxplot

import pandas as pd
df = pd.DataFrame(rand(100, 1), columns=['value'])
df.ix[:23, 'class']='A'
df.ix[24:, 'class']='B'
df.boxplot(column='value', by='class')

boxplot What I'd like is to show the sample size of each class A and B, namely 24 and 76 respectively. It could appear as legend or somewhere near the boxes, either is ok with me.

Thanks!

3
  • I do not really understand what you would like to do... Can you give an example? Mar 26, 2015 at 20:33
  • 1
    Your proposed solution would be a two-liner, wouldn't it? Calculate the sizes (I assume n) from the groupby, pass them as (say) a labels kwarg? Not bad.
    – cphlewis
    Mar 27, 2015 at 2:26
  • answered here: python-graph-gallery.com/…
    – fstang
    Dec 8, 2021 at 7:34

1 Answer 1

8

n in the class ticklabels. I tried it as a legend but I didn't think it was as clear. R has a lot more boxplot options, including making the width of the boxes proportional to sample size; not a default in matplotlib but easy and seems really readable:

import pandas as pd
from numpy.random import rand, randint

df = pd.DataFrame(rand(100, 1), columns=['value'])

cut1 = randint(2,47)
cut2 = randint(52, 97)
df.ix[:cut1, 'class']='A'
df.ix[cut1+1:cut2, 'class']='B'
df.ix[cut2+1:, 'class'] = 'C'

dfg = df.groupby('class')

counts = [len(v) for k, v in dfg]
total = float(sum(counts))
cases = len(counts)

widths = [c/total for c in counts]  

cax = df.boxplot(column='value', by='class', widths=widths)
cax.set_xticklabels(['%s\n$n$=%d'%(k, len(v)) for k, v in dfg])

enter image description here

3
  • Nice. I would suggest a minor change giving nicer widths in some cases: widths = [c/max(counts) for c in counts]
    – n1000
    Nov 3, 2017 at 16:00
  • When (and why) do you think those widths are nicer?
    – cphlewis
    Nov 3, 2017 at 18:13
  • 1
    when there is many categories the small ones become a very thin line
    – n1000
    Nov 3, 2017 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.