Reputation: 67
how to add labels to a horizontal bar chart in matplotlib?
Hi everyone, I'm a matplotlib and python newbie and I wanted to ask this question again to get a bit of help as to if there are easier ways to add labels for the count represented by each bar than the current solutions I've found.
Here is the code I have written:
from matplotlib.pyplot import figure
figure(num=None, figsize=(8, 24), dpi=80, facecolor='w', edgecolor='k')
df['Name'].value_counts()[:80].plot(kind='barh')
It works just fine, except for the showing labels next to the bars bit...
I looked on here how to add the label and so I change my code to this:
x = df['Name']
y = df['Name'].value_counts(ascending=True)
fig, ax = plt.subplots(figsize=(18,20))
width = 0.75 # the width of the bars
ind = np.arange(len(y)) # the x locations for the groups
ax.barh(ind, y, width, color="blue")
ax.set_yticks(ind+width/2)
ax.set_yticklabels(y, minor=False)
plt.title('Count of supplies')
plt.xlabel('Count')
plt.ylabel('ylabel')
for i, v in enumerate(y):
ax.text(v + 100, i + 0, str(v), color='black', fontweight='bold')
However, now my names aren't associated with the bars and are just like in order they appear within the dataframe. is there a way to just simply change the first code or to make it so the names associated with bars are correct in 2nd attempt (grouped with the bar they are labeling..)?
Image sorta explaining my issue:
Upvotes: 2
Views: 14867
Reputation: 80279
Using the index of y as the index of the barh plot should put the y-labels on the correct spot, next to the corresponding bar. There's no need to manipulate the y-ticklabels. The bar labels can be left aligned and vertically centered. The right x-limit may be moved a bit to have room for the label of the longest bar.
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame({'Name': np.random.choice(list('AABBBBBCCCCCDEEF'), 20000)})
y = df['Name'].value_counts(ascending=False)
fig, ax = plt.subplots(figsize=(12,5))
ax.barh(y.index, y, height=0.75, color="slateblue")
plt.title('Count of supplies')
plt.xlabel('Count')
plt.ylabel('ylabel')
_, xmax = plt.xlim()
plt.xlim(0, xmax+300)
for i, v in enumerate(y):
ax.text(v + 100, i, str(v), color='black', fontweight='bold', fontsize=14, ha='left', va='center')
plt.show()
Upvotes: 4