【问题标题】:Annotate bars with values on Pandas bar plots for subplots用 Pandas 条形图上的值注释条形以获取子图
【发布时间】:2020-02-09 01:15:03
【问题描述】:

我正在尝试在 pandas 条形图中注释条形。我的以下代码适用于没有子图的单个图,但不幸的是不适用于子图。

    df=pd.DataFrame({'A':np.random.rand(2),'B':np.random.rand(2)},index=['2018-10-30 12:00:00','2018-10-30 12:15:00',] )         
print(df)

fig, ax = plt.subplots()

df.plot.bar(ax=ax, title='My Barplots',subplots = False, sharex=True, sharey=True)
for p in ax.patches:
    ax.annotate(str(round(p.get_height(),2)), (p.get_x() * 1.005, p.get_height() * 1.005))

plt.gcf().autofmt_xdate()
plt.show()

当我将“subplots = False”更改为“subplots = True”时,注释不再显示。

任何人都可以帮助如何使用子图进行这项工作吗?

【问题讨论】:

  • ax 必须是您希望注释所在的子图。 df.plot 返回这些子图的数组,因此您需要为每个子图执行此操作。
  • UserWarning: To output multiple subplots, the figure containing the passed axes is being cleared
  • 感谢 ImportanceOfBeingErnest 和 Quang Hoang 引导我找到解决方案。

标签: python-3.x pandas matplotlib bar-chart


【解决方案1】:

感谢您的 cmets。现在我找到了解决办法。

    df=pd.DataFrame({'A':np.random.rand(2),'B':np.random.rand(2)},index=['2018-10-30 12:00:00','2018-10-30 12:15:00',] )         
print(df)

axes = df.plot.bar( title='My Barplots',subplots = True, sharex=True, sharey=True)
for ax in axes:
    for p in ax.patches:
        ax.annotate(str(round(p.get_height(),2)), (p.get_x() * 1.005, p.get_height() * 1.005))

plt.gcf().autofmt_xdate()
plt.show()

我现在已经在图形的轴上进行了第二次循环。这行得通。

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 2017-01-23
    • 2016-03-10
    相关资源
    最近更新 更多