【问题标题】:Add text to figure using python's plotnine使用 python 的 plotnine 向图形添加文本
【发布时间】:2019-11-25 01:08:52
【问题描述】:

我想给 plotnine 中的一行添加一个标签。使用 geom_text 时出现以下错误:

'NoneType' object has no attribute 'copy'

示例代码如下:

df = pd.DataFrame({
    'date':pd.date_range(start='1/1/1996', periods=4*25, freq='Q'),
    'small': pd.Series([0.035]).repeat(4*25) ,
    'large': pd.Series([0.09]).repeat(4*25),
})


fig1 = (ggplot()
    + geom_step(df, aes(x='date', y='small'))
    + geom_step(df, aes(x='date', y='large'))
    + scale_x_datetime(labels=date_format('%Y')) 
    + scale_y_continuous(labels=lambda l: ["%d%%" % (v * 100) for v in l])
    + labs(x=None, y=None) 
    + geom_text(aes(x=pd.Timestamp('2000-01-01'), y = 0.0275, label = 'small'))
)

print(fig1)

编辑:

has2k1's answer below解决了错误,但我得到了:

我想要这个:(来自 R)

R 代码:

ggplot() + 
  geom_step(data=df, aes(x=date, y=small), color='#117DCF', size=0.75) +
  geom_step(data=df, aes(x=date, y=large), color='#FF7605', size=0.75) +
  scale_y_continuous(labels = scales::percent, expand = expand_scale(), limits = c(0,0.125)) +
  labs(x=NULL, y=NULL) +  
  geom_text(aes(x = as.Date('1996-01-07'), y = 0.0275, label = 'small'), color = '#117DCF', size=5)

https://plotnine.readthedocs.io/en/stable/index.html 之外的任何文档?我已经阅读了那里的 geom_text,但仍然无法产生我需要的东西......

【问题讨论】:

    标签: python python-3.x plotnine


    【解决方案1】:

    geom_text 没有数据框。如果您想打印文本,请将其放在引号中,即 '"small"' 或将标签映射放在 aes() 之外,但使用 annotate 更有意义。

    (ggplot(df)
     ...
     # + geom_text(aes(x=pd.Timestamp('2000-01-01'), y = 0.0275, label = '"small"'))
     # + geom_text(aes(x=pd.Timestamp('2000-01-01'), y = 0.0275), label = 'small')
     + annotate('text', x=pd.Timestamp('2000-01-01'), y = 0.0275, label='small')
    )
    

    【讨论】:

    • 谢谢。那太棒了!语法与 R 稍有不同。如何找出这些东西?我查看了 plotnine 网站,找不到有用的示例(尽管我没有查看注释,因为我也是 R 新手,所以没有遇到过)。但是是否有其他文件可供阅读?比如,你怎么知道将标签放在 aes 标签之外或放在双引号中会起作用?
    • @brb,好问题。由于 R 和 python 的差异,plotnine 的评估系统不同。我刚刚意识到文档中没有一个地方可以全面地列出它。 aes() 文档尝试过,但需要很好地掌握 Python 才能推断出此类问题。解决方案是仅此方面的专门教程。我添加了issue
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2018-06-29
    • 2021-08-23
    • 2020-03-27
    相关资源
    最近更新 更多