【问题标题】:How to add geom_hlines legend into plot in plotnine?如何将 geom_hlines 图例添加到 plotnine 的图中?
【发布时间】:2019-10-18 17:08:33
【问题描述】:

我想在我的情节中添加一个包含所有 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')

    )

【问题讨论】:

标签: python r plotnine


【解决方案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)
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多