用中值标记箱图

时间:2017-08-03 05:57:46

标签: python matplotlib seaborn boxplot

除了在this link中发布的解决方案之外,如果我还可以添加Hue参数,并在每个图中添加中值,还可以。

现行守则:

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

提供类似:enter image description here

的输出

我正在研究可以在this link找到的泰坦尼克号数据集。

我获得了所需的值,但只有在我执行print语句时,如何将其包含在我的Plot中?

1 个答案:

答案 0 :(得分:5)

根据所有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