简体   繁体   中英

Add text to figure using python's plotnine

I would like to add a label to a line in plotnine. I get the following error when using 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)

Edit:

has2k1's answer below solves the error, but I get:

在此处输入图片说明

I want this: (from R)

R code:

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)

在此处输入图片说明

Any documentation beyond https://plotnine.readthedocs.io/en/stable/index.html ? I have read the geom_text there and still can't produce what I need...

geom_text has no dataframe. If you want to print the text put it in quotes ie '"small"' or put the label mapping outside aes() , but it makes more sense to use 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')
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM