Python: Pandas链接:如何将文本添加到绘图?

huangapple go评论72阅读模式
英文:

Python : Pandas Chaining : How to add text to the plot?

问题

抱歉,我无法执行代码。要在条形图上添加文本标签,你可以使用Matplotlib库。下面是在使用Pandas链接时添加标签的示例代码:

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

# 添加标签到条形图
import matplotlib.pyplot as plt

# 假设你的unstacked数据框为df_unstacked
df_unstacked = df.groupby(['col1', 'col2'], dropna=False)[['col1', 'col2']].size().unstack()

# 从unstacked数据框中获取行数和列数
rows, cols = df_unstacked.shape

for i in range(cols):
    for j in range(rows):
        # 检查数值是否为NaN,如果不是,添加文本标签到条形图
        if not pd.isnull(df_unstacked.iloc[j, i]):
            plt.text(i, df_unstacked.iloc[j, i], str(df_unstacked.iloc[j, i]), ha='center', va='bottom')

plt.show()

以上代码会在条形图上的每个条形上添加相应的数字标签。

英文:

How to add text/label to a bar plot, when using pandas chaining ? Below is how I'm plotting without the label.

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

The unstacked data frame (right before .plot in the above code) has data as below.

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

The plot is as below:
Python: Pandas链接:如何将文本添加到绘图?

I would like to have the numbers displayed on top of the bars. Please advice. Thank you.

答案1

得分: 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)


输出:

[![enter image description here][1]][1]

**更新**

> 我正在使用 3.3.2 版本,由于系统限制,无法升级

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


  [1]: https://i.stack.imgur.com/CV08j.png
英文:

You have to get the output of your chaining (return an Axes instance):

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)

Output:

Python: Pandas链接:如何将文本添加到绘图?

Update

> I'm using 3.3.2 and cannot upgrade due to system restrictions

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')

huangapple
  • 本文由 发表于 2023年2月7日 04:26:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定