如何在plotnine中的plot中添加geom\u hlines图例?

2024-04-25 06:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为我的情节添加一个传奇,其中包含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')

    )

Tags: test信息ageplot传奇coloraes情节
1条回答
网友
1楼 · 发布于 2024-04-25 06:21:53

在大多数情况下,当你发现自己在与传奇抗争时,这表明你正在绘制的数据没有得到有意义的安排。图例旨在帮助解释映射的变量。在您的例子中,所有这些水平线都可以用一个变量表示,即“年龄统计”。你知道吗

然后,解决方案是将它们放在一个数据帧中,并使用一个对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)
)

相关问题 更多 >