标签(注释)在pandas地区中

2024-09-20 01:37:43 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以在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')

下面是我如何绘制堆积面积图

^{pr2}$

Snippet of the stacked area chart for percentage share plotted using above code

任何线索都将不胜感激。为了说明我的想法,它类似于this图像,但在堆积面积图中(沿着绘图的数据标签,类似于问题中的第一个代码)。在


Tags: 数据inpandasforgetmatplotlib标签label
1条回答
网友
1楼 · 发布于 2024-09-20 01:37:43

可以手动将批注添加到堆积面积图中,使用值的累积和来计算标签的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')

enter image description here

相关问题 更多 >