python - 使用 python 的plotnine 将文本添加到图中

标签 python python-3.x plotnine

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

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 但仍然无法生成我需要的内容...

最佳答案

geom_text 没有数据框。如果您想打印文本,请将其放在引号中,即“小”,或者将标签映射放在 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')
)

关于python - 使用 python 的plotnine 将文本添加到图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59024019/

相关文章:

python - 自定义权重初始化 tensorflow tf.layers.dense

python 情节9: how to change color scale

python - Streamlit 和 ContainDS ImportError : Failed to initialize: Bad git executable

Python ctypes 位域

python - 如何在 python selenium 的 css 选择器中包含正则表达式

python 情节9: color brewer not enough

python - 如何获取 SQL Alchemy 执行的查询的原始 SQL

python-3.x - 所以我想将 ffmpeg 与 heroku 一起使用,但我不断收到我没有安装 ffmpeg 的错误

不支持 python opencv 格式