如何将 geom_hlines 图例添加到 plotnine 的图中?

我想在我的情节中添加一个图例,其中包含所有 hline 的统计描述。有什么办法吗?

def test_plot():

Q1=test['age'].quantile(0.25)

Q3=test['age'].quantile(0.75)

IQR=Q3-Q1

fig = (

    ggplot(test) +

    aes(x=arr,y='age')+

    geom_point()+

    labs(

        title='Test',

        x='Index',

        y='Age',

        )+

    geom_hline(aes(yintercept =test.age.mean(),),color = 'gray')+

    geom_hline(aes(yintercept =test.age.median()),color = 'green')+

    geom_hline(aes(yintercept =IQR),color = 'blue')+

    geom_hline(aes(yintercept =test['age'].quantile(0.1)),color= 'red')+

    geom_hline(aes(yintercept =test['age'].quantile(0.9)),color= 'yellow')+

    geom_hline(aes(yintercept =test['age'].std()),color= 'purple')


    )


至尊宝的传说
浏览 113回答 1
1回答

青春有我

在大多数情况下,当您发现自己与图例作斗争时,这表明您正在绘制的数据没有被有意义地排列。图例旨在帮助解释映射变量。在您的情况下,所有这些水平线都可以用一个变量表示,即“年龄统计”。然后解决方案是将它们放入数据框中并使用一次调用,geom_hline以便绘图系统可以处理图例。sdf = pd.DataFrame({    'age_statistic': [         'mean', 'median', IQR,         '10th Percentile', '90th Percentile',         'std'    ],    'value' : [         test.age.mean(), test.age.median(), IQR,         test['age'].quantile(0.1), test['age'].quantile(0.9),         test['age'].std()    ]})(ggplot(...) ... + geom_hline(sdf, aes(yintercept='value', colour='age_statistic'), show_legend=True))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python