【发布时间】: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