首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Plotnine (ggplot):标绘区域外的注释

Plotnine (ggplot):标绘区域外的注释
EN

Stack Overflow用户
提问于 2021-11-10 13:43:31
回答 1查看 499关注 0票数 1

我在plotnine中有下面的情节。我想在y轴的左边添加一个标签,显示该系列的平均值(基本上与y轴标签一致)。更好的是,如果标签可以按照下面的形状,指向平均线。这个是可能的吗?

代码语言:javascript
复制
import numpy as np
import pandas as pd
import datetime
from plotnine import *


df = pd.DataFrame({
    'date':pd.date_range(start='1/1/2000', periods=10, freq='A'),
    'a': np.random.choice(range(20),10),
    'b': np.random.choice(range(20),10),
})

mean_a = df['a'].mean()
mean_b = df['b'].mean()

df = pd.melt(df,id_vars=['date'])

p = (ggplot(df, aes(x='date', y='value', fill='variable'))
  + theme_light()
  + geom_col(position='dodge', alpha=0.8)
  + geom_hline(yintercept=mean_a, linetype='dotted', color='#770d50', size=1.5)
  + geom_hline(yintercept=mean_b, linetype='dotted', color='#0055b3', size=1.5)
  + annotate('label', x=datetime.datetime(2010, 10, 1), y=mean_a, label='{:.1f}'.format(mean_a), color='#770d50', size=8, label_size=0.2)
  + annotate('label', x=datetime.datetime(2010, 10, 1), y=mean_b, label='{:.1f}'.format(mean_b), color='#0055b3', size=8, label_size=0.2)
  + annotate('label', x=datetime.datetime(2011, 1, 1), y=mean_b, label='')
  + scale_x_date(expand=(0,0), labels= lambda l: [v.strftime("%Y") for v in l])
  + scale_fill_manual(('#770d50','#0055b3'))
)
p

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-04 02:08:18

正如所描述的这里,您可以使用ggplot对象的draw方法获得matplotlib图。然后,您可以使用轴和传统matplotlib函数来使用ax.textax.annotate函数绘制所需的注释,如下所示。您可能需要使用文本的实际x位置。

代码语言:javascript
复制
# original graph
p = (ggplot(df, aes(x='date', y='value', fill='variable'))
  + theme_light()
  + geom_col(position='dodge', alpha=0.8)
  + geom_hline(yintercept=mean_a, linetype='dotted', color='#770d50', size=1.5)
  + geom_hline(yintercept=mean_b, linetype='dotted', color='#0055b3', size=1.5)
  + annotate('label', x=datetime.datetime(2010, 10, 1), y=mean_a, label='{:.1f}'.format(mean_a), color='#770d50', size=8, label_size=0.2)
  + annotate('label', x=datetime.datetime(2010, 10, 1), y=mean_b, label='{:.1f}'.format(mean_b), color='#0055b3', size=8, label_size=0.2)
  + annotate('label', x=datetime.datetime(2011, 1, 1), y=mean_b, label='')
  + scale_x_date(expand=(0,0), labels= lambda l: [v.strftime("%Y") for v in l])
  + scale_fill_manual(('#770d50','#0055b3'))
)

# graph with annotation
fig = p.draw() # get the matplotlib figure object
ax = fig.axes[0] # get the matplotlib axis (may be more than one if faceted)
x_ticks = ax.get_xticks() # get the original x tick locations
x_loc = x_ticks.min() - (sorted(x_ticks)[1] - sorted(x_ticks)[0])*.75 # location for the annotation based on the original xticks
# annotation for mean_a using text
ax.text(x_loc,mean_a,'{:.2f}'.format(mean_a),
        horizontalalignment='right',verticalalignment='center',
        color='#770d50')
# annotation for mean_b using annotate with an arrow
ax.annotate(xy=(x_ticks.min(),mean_b),
            xytext=(x_loc,mean_b+.5),text='{:.2f}'.format(mean_b),
        horizontalalignment='right',verticalalignment='center',
        arrowprops={'arrowstyle':'->'},
        color='#0055b3')

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69914374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档