1

I want to add median labels to my boxplots, but can't figure out the right code to do so in Seaborn.

I tried two different solutions that I found here and here, but neither worked. My code is below, using the first solution:

import seaborn as sns
sns.set()
sns.set(rc={'figure.figsize':(40,24)})
sns.set(font_scale=3)
sns.set_style("whitegrid")

ax = sns.boxplot(x="Year", y="Travel Time", data=Potrero_fall_PM_OB_clean, 
showfliers=False).set(xlabel='Year', ylabel='Travel Time (min)', title = 
"Fall PM OB Travel Time on Potrero Ave, Year over Year")

medians = Potrero_fall_PM_OB_clean.groupby(['Year'])['Travel 
Time'].median().values
median_labels = [str(np.round(s, 2)) for s in medians]

pos = range(len(medians))
for tick,label in zip(pos,ax.get_xticklabels()):
    ax.text(pos[tick], medians[tick] + 0.5, median_labels[tick], 
            horizontalalignment='center', size='x-small', color='w', 
            weight='semibold')

I hoped to get a boxplot with median labels, but I get this:


AttributeError                            Traceback (most recent call last)
<ipython-input-36-ce75d0ad015b> in <module>
     12 
     13 pos = range(len(medians))
---> 14 for tick,label in zip(pos,ax.get_xticklabels()):
     15     ax.text(pos[tick], medians[tick] + 0.5, median_labels[tick], 
     16             horizontalalignment='center', size='x-small', 
     color='w', weight='semibold')

 AttributeError: 'list' object has no attribute 'get_xticklabels'

I don't understand why it doesn't have get_xticklabels attribute. How can I fix this and get the medians to show up on my boxplot?

Michael M.
  • 11
  • 2
  • You did not provide [a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) so running your current code is not possible. Nevertheless, it seems like the axis object `ax` is not a single object but is a list of more than one axis object, possible a list of axis objects corresponding to subplots. You can check it by looking at the size of `ax` using `print (ax.shape)`. It will most probably be more than `1`. This could be the reason you are getting the attribute error because if it's more than 1, then you'll have to loop over individual objects and then get x-labels – Sheldore Feb 16 '19 at 23:05
  • The problem is rather that `ax.set()` does not return an axes. You should separate you commands, first call `ax = sns.boxplot(...)` then call `ax.set(...)` then the rest of the code might work. – ImportanceOfBeingErnest Feb 16 '19 at 23:29
  • @ImportanceOfBeingErnest This solution worked! Thanks for your help! – Michael M. Feb 20 '19 at 00:46

0 Answers0