Plotnine(ggplot)实现绘图区域外y轴左侧添加指向均值线的标注
这个需求完全可以实现,核心思路是关闭绘图区域裁剪、预留左侧边距,再分别添加指向均值线的箭头和对应数值标注即可。修改后的完整代码如下:
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() # 调整左边距,预留标注位置 + theme(plot_margin=dict(left=2)) + 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) # 关闭裁剪,允许绘图区外显示元素 + coord_cartesian(clip="off") # 添加指向a序列均值线的箭头 + annotate("segment", x=datetime.datetime(1999,6,1), xend=datetime.datetime(1999,12,1), y=mean_a, yend=mean_a, color='#770d50', arrow=arrow(angle=15, length=0.1, type="closed")) # 添加a序列均值标注 + annotate('label', x=datetime.datetime(1998,12,1), y=mean_a, label='{:.1f}'.format(mean_a), color='#770d50', size=8, label_size=0.2) # 添加指向b序列均值线的箭头 + annotate("segment", x=datetime.datetime(1999,6,1), xend=datetime.datetime(1999,12,1), y=mean_b, yend=mean_b, color='#0055b3', arrow=arrow(angle=15, length=0.1, type="closed")) # 添加b序列均值标注 + annotate('label', x=datetime.datetime(1998,12,1), y=mean_b, label='{:.1f}'.format(mean_b), color='#0055b3', size=8, label_size=0.2) + scale_x_date(expand=(0,0), labels= lambda l: [v.strftime("%Y") for v in l]) + scale_fill_manual(('#770d50','#0055b3')) ) p
核心修改说明
theme(plot_margin=dict(left=2)):给画布左侧预留足够空间放置标注,避免内容被截断coord_cartesian(clip="off"):关闭绘图区域的默认裁剪规则,允许在坐标轴外侧渲染元素- 新增的
annotate("segment")层:绘制带箭头的线段,箭头指向对应均值线的左端 - 调整标注的x坐标至x轴刻度范围左侧,和y轴标签处于同一列位置
内容的提问来源于stack exchange,提问作者brb
相关产品推荐
相关产品推荐

