【问题标题】:Add value text for value_counts().plot in Matplotlib [duplicate]在 Matplotlib 中为 value_counts().plot 添加值文本 [重复]
【发布时间】:2021-08-18 14:51:23
【问题描述】:

给出如下代码:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(['A','A','A','B','B','C'], columns = ['letters'])
df.value_counts()
df.letters.value_counts().sort_values().plot(kind = 'bar')

输出:

我想为每个条添加值文本,我怎么能在 Matplotlib 中做到这一点?谢谢。

更新的代码和数据集:

给定一个小数据集如下:

  letters  numbers
0       A       10
1       A        4
2       A        3
3       B       12
4       B        7
5       C        9
6       C        8

代码:

import pandas as pd
import matplotlib.pyplot as plt

bins = [0, 5, 10, 20]
df['binned'] = pd.cut(df['numbers'], bins = bins)

def addlabels(x, y):
    for i in range(len(x)):
        plt.text(i, y[i], y[i])

plt_df = df.binned.value_counts().sort_values()
plt.bar(plt_df.index, plt_df.values)
addlabels(plt_df.index, plt_df.values)

输出:

TypeError: float() argument must be a string or a number, not 'pandas._libs.interval.Interval'

【问题讨论】:

  • 你的意思是像Value = 2 在每个栏的顶部吗?
  • 是的,正好在每个条的顶部添加值。
  • 您必须确定计数并添加它们,如 here 所示。

标签: python-3.x pandas matplotlib


【解决方案1】:

试试:

import pandas as pd
import matplotlib.pyplot as plt

def addlabels(x,y):
    for i in range(len(x)):
        plt.text(i, y[i], y[i], ha = 'center')

df = pd.DataFrame(['A','A','A','B','B','C'], columns = ['letters'])
plt_df = df.letters.value_counts().sort_values()

plt.bar(plt_df.index, plt_df.values)
addlabels(plt_df.index, plt_df.values)

【讨论】:

  • 当然,我会,但是用我的真实数据进行测试,它会引发错误:TypeError: float() argument must be a string or a number, not 'pandas._libs.interval.Interval'df.letters 被替换为从df['binned'] = pd.cut(df['counts'], bins = bins) 获得的df['binned']
  • 你能帮忙解决这个问题吗?
  • 垃圾箱是什么?分享您的数据集。
  • 我更新了数据和代码,请检查。
  • 使用pd.cut(df['numbers'], bins = bins).astype(str)解决的问题,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 2022-12-14
  • 1970-01-01
  • 2020-12-01
  • 2013-03-03
  • 2022-01-11
  • 2020-10-26
相关资源
最近更新 更多