【问题标题】:Labeling boxplot with median values用中值标记箱线图
【发布时间】:2017-08-03 05:57:46
【问题描述】:

除了this link 中发布的解决方案之外,我还想添加色调参数,并在每个图中添加中值。

当前代码:

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

输出类似:

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

我得到了所需的值,但只有在我执行打印语句时,我如何将它包含在我的绘图中?

【问题讨论】:

    标签: python matplotlib seaborn boxplot


    【解决方案1】:

    在所有 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()
    

    【讨论】:

      猜你喜欢
      • 2016-12-03
      • 2021-11-06
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 2017-04-10
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多