3

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:

enter image description here

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)

enter image description here

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...

brb
  • 1,123
  • 17
  • 40

1 Answers1

6

geom_text has no dataframe. If you want to print the text put it in quotes i.e. '"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')
)
has2k1
  • 2,095
  • 18
  • 16
  • 1
    Thanks. That's great! Syntax a little different to R. How does one find these things out? I looked at the plotnine website and could not find an example that would have helped (albeit I did not look at annotate as I am new to R as well so had not come across it). But is there additional documentation to read? Like, how did you know that putting label outside of the aes label or in double quotes would work? – brb Nov 30 '19 at 23:46
  • 2
    @brb, good question. The evaluation system different in plotnine because of the differences between R and python. I just realised there isn't a place in the documentation that comprehensively lays it out. The `aes()` documentation tries but one would need to have a good grasp of python to infer such issues. The solution is a dedicated tutorial on this aspect alone.I have added an [issue](https://github.com/has2k1/plotnine/issues/334). – has2k1 Dec 01 '19 at 12:29