是否可以在pandas / matplotlib堆积面积图中放置数据标签(值)?
在堆积条形图中,我使用以下
for label in yrplot.patches:
yrplot.annotate(label.get_height(), (label.get_x()+label.get_width()/2.,label.get_y()+label.get_height()/2.),
ha='center', va='center', xytext=(0, 1),
textcoords='offset points')
下面是我如何绘制堆积面积图
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
yrplot = yrly_perc_df.plot(x='year', y=prod, kind='area', stacked=True, figsize=(15,10), color = areacolors)
yrplot.set_ylabel('share')
yrplot.legend(loc='center left', bbox_to_anchor=(1.0,0.5))
任何线索都将不胜感激。为了说明我的需求,它类似于 this 图像,但在堆积面积图中(图上的数据标签,类似于问题中的第一个代码)。
答案 0 :(得分:2)
可以使用值的累加总和来计算标签的y位置,从而将注释手动添加到堆积面积图。另外,如果堆栈的高度很小,建议不要绘制注释。
rs = np.random.RandomState(12)
values = np.abs(rs.randn(12, 4).cumsum(axis=0))
dates = pd.date_range("1 1 2016", periods=12, freq="M")
data = pd.DataFrame(values, dates, columns=["A", "B", "C", "D"])
ax = data.plot(kind='area', stacked=True)
ax.set_ylabel('value')
ax.legend(loc='center left', bbox_to_anchor=(1.0,0.5))
for x1 in data.index:
# Y positions are given by the cumulative sum of the values, plus half of the height of the specific stack
yCenteredS = data.loc[x1].cumsum()
yCenteredS = [0.0] + yCenteredS.tolist()
yCenteredS = [y + (yCenteredS[i+1] - y)/2. for i, y in enumerate(yCenteredS[:-1])]
# Draw the values as annotations
labels = pd.DataFrame(data={'y':yCenteredS, 'value':data.loc[x1].tolist()})
# Don't draw the annotation if the stack is too small
labels = labels[labels['value'] > 0.5]
for _, y, value in labels.itertuples():
ax.annotate('{:.2f}'.format(value), xy=(x1, y), ha='center', va='center',
bbox=dict(fc='white', ec='none', alpha=0.2, pad=1),
fontweight='heavy', fontsize='small')