【问题标题】:Python : Pandas Chaining : How to add text to the plot?Python:Pandas Chaining:如何向情节添加文本?
【发布时间】:2023-02-07 05:19:02
【问题描述】:

如何将文本/标签添加到条形图,使用熊猫链接时?下面是我如何在没有标签的情况下进行绘图。

(
  df
  .groupby(['col1','col2'], dropna=False)
  [['col1', 'col2']]
  .size()
  .unstack()
  .plot(kind='bar', figsize = (8,8))
 )

未堆叠的数据框(就在上面代码中的 .plot 之前)具有如下数据。

col2    1.0     2.0     3.0     4.0     NaN
col1
 1.0    514    1922    7827   18877    1966
 2.0    NaN     NaN     NaN     NaN    2018
 NaN     21      20      59      99    5570

情节如下:

我想让数字显示在条形图的顶部。请指教。谢谢。

【问题讨论】:

    标签: python pandas dataframe plot chaining


    【解决方案1】:

    您必须获得链接的输出(返回一个 Axes 实例):

    ax = (df.groupby(['col1', 'col2'], dropna=False)[['col1', 'col2']]
            .size().unstack()
            .plot(kind='bar', figsize=(8, 8)))
    
    for bars in ax.containers:
        ax.bar_label(bars)
    

    输出:

    更新

    我使用的是 3.3.2,由于系统限制无法升级

    for rect in ax.patches:
        height = rect.get_height()
        ax.annotate(r'{:d}'.format(int(height)),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),
                    textcoords="offset points",
                    ha='center', va='bottom')
    

    【讨论】:

    • 谢谢科拉林的回复。但看起来 bar_label 与 matplotlib 版本 3.4 及更高版本一起出现。不幸的是,我使用的是 3.3.2,由于系统限制无法升级。还有其他方法可以完成这项工作吗?
    • @Geeths matplotlib.org/3.3.2/gallery/lines_bars_and_markers/…也许这会帮助你解决问题
    • @Geeths。我更新了我的答案,你能检查一下吗?
    猜你喜欢
    • 2016-11-03
    • 2019-04-25
    • 1970-01-01
    • 2015-04-21
    • 2017-05-26
    • 2014-10-26
    • 2018-10-22
    • 2021-04-14
    • 2017-03-30
    相关资源
    最近更新 更多