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

How to add geom_hlines legend into plot in plotnine?

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

Link to plot

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

    )

在大多数情况下,当你发现自己在和传奇打架时,这表明你正在绘制的数据没有被有意义地安排。图例旨在帮助解释映射变量。在您的情况下,所有这些水平线都可以由一个变量表示,即 "age statistic".

然后解决方案是将它们放入数据框中并调用一次 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)
)