使用Python的plotnine在图形中添加文本

3
我想在plotnine中的一条线上添加标签。当使用geom_text时,我会收到以下错误提示:
'NoneType' object has no attribute 'copy'

Sample code below:

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的答案解决了错误,但我得到了:

enter image description here

我想要这个:(来自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)

enter image description here

除了https://plotnine.readthedocs.io/en/stable/index.html之外,还有其他关于编程的文档吗?我已经阅读了geom_text的相关内容,但仍无法得到我所需的结果...

1个回答

6

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

1
谢谢。太好了!语法与R有点不同。怎么才能找到这些东西?我看了plotnine网站,没有找到一个有用的例子(虽然我没有看annotate,因为我也是新手,所以还没有接触它)。但是是否有额外的文档可以阅读?比如说,你是怎么知道将标签放在aes标签外面或双引号中会起作用的? - brb
2
@brb,好问题。由于R和Python之间的差异,plotnine中的评估系统不同。我刚意识到文档中没有一个全面阐述这一点的地方。aes()文档尝试了解,但需要对Python有很好的掌握才能推断出这些问题。解决方案是专门针对这个方面的教程。我已经添加了一个问题 - has2k1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接