0

Given a code as follows:

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

Out:

enter image description here

I would like to add value text for each bar, how could I do that in Matplotlib? Thanks.

Updated code and dataset:

Given a small dataset as follows:

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

Code:

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)

Output:

TypeError: float() argument must be a string or a number, not 'pandas._libs.interval.Interval'
ah bon
  • 9,293
  • 12
  • 65
  • 148

1 Answers1

1

Try:

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)

enter image description here

ah bon
  • 9,293
  • 12
  • 65
  • 148
Hamza usman ghani
  • 2,264
  • 5
  • 19