Issue
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:
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'
Solution
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)
Answered By - Hamza usman ghani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.