Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Labeling boxplot with median values

In addition to the solution posted in this link I would also like if I can also add the Hue Parameter, and add the Median Values in each of the plots.

The Current Code:

testPlot = sns.boxplot(x='Pclass', y='Age', hue='Sex', data=trainData)
m1 = trainData.groupby(['Pclass', 'Sex'])['Age'].median().values
mL1 = [str(np.round(s, 2)) for s in m1]
p1 = range(len(m1))

for tick, label in zip(p1, testPlot.get_xticklabels()):
    print(testPlot.text(p1[tick], m1[tick] + 1, mL1[tick]))

Gives a Output Like: enter image description here

I'm working on the Titanic Dataset which can be found in this link.

I'm getting the required values, but only when I do a print statement, how do I include it in my Plot?

like image 498
Mr. Hobo Avatar asked Aug 03 '17 05:08

Mr. Hobo


1 Answers

Place your labels manually according to hue parameter and width of bars for every category in a cycle of all xticklabels:

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pylab as plt

trainData = pd.read_csv('titanic.csv')
testPlot = sns.boxplot(x='pclass', y='age', hue='sex', data=trainData)
m1 = trainData.groupby(['pclass', 'sex'])['age'].median().values
mL1 = [str(np.round(s, 2)) for s in m1]

ind = 0
for tick in range(len(testPlot.get_xticklabels())):
    testPlot.text(tick-.2, m1[ind+1]+1, mL1[ind+1],  horizontalalignment='center',  color='w', weight='semibold')
    testPlot.text(tick+.2, m1[ind]+1, mL1[ind], horizontalalignment='center', color='w', weight='semibold')
    ind += 2    
plt.show()

enter image description here

like image 169
pcu Avatar answered Nov 15 '22 06:11

pcu