【问题标题】:Labels (annotate) in pandas area plot熊猫区域图中的标签(注释)
【发布时间】:2019-01-12 18:04:17
【问题描述】:

是否可以在 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 图像,但在堆积面积图中(图中的数据标签,类似于问题中的第一个代码)。

【问题讨论】:

  • 你想要的输出是什么?
  • 我想要图表上的年度百分比值,就像条形图的注释一样。面积图可以吗?
  • 这是否满足您的需求? stackoverflow.com/questions/31573869/…
  • 链接无效。此外,您应该首先尝试发布您想要的内容,以便有更多机会获得答案。
  • @samkart 你真的应该在你的问题中包含你想要的结果。我没有打开你的谷歌文档!另外:最小的工作示例?

标签: python pandas matplotlib


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2015-05-04
    相关资源
    最近更新 更多