Reputation: 199
I use the below code in order to display the bar chart.
CODE
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#creating the dataset
data = {'apples':20,'Mangoes':15,'Lemon':30,'Oranges':10}
names = list(data.keys())
values = list(data.values())
bars = plt.bar(names, height=values, width=0.9)
for bar in bars:
yval = bar.get_height()
plt.text(bar.get_x(), yval + .005, yval)
plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = True
plt.show()
OUTPUT
My requirement is i want the labels aligned in the center of each bar and has to sorted in descending order. Looking for Output like below.
Upvotes: 0
Views: 1649
Reputation: 9
you can use this code to fix your problem. your arbitrary bar chart figure
%matplotlib notebook
import matplotlib.pyplot as plt
data = {'apples' : 20, 'Mangoes' : 15,
'Lemon' : 30, 'oranges' : 10}
# we apply asterisk sign on a list of tuples which is returened by
# sorted() function.
names, values = zip(*sorted(data.items(), key= lambda x: x[1], reverse=True))
plt.figure()
plt.bar(names, values, width=0.9)
# add Bar labels
for c in plt.gca().containers:
plt.gca().bar_label(c)
plt.show()
Called with a BarContainer artist, add a label to each bar, which, by default, is data value, so exactly what you want.
Upvotes: 1
Reputation: 82765
To sort use:
import numpy as np
import matplotlib.pyplot as plt
#creating the dataset
data = {'apples':20,'Mangoes':15,'Lemon':30,'Oranges':10}
names, values = zip(*sorted(data.items(), key=lambda x: x[1], reverse=True))
bars = plt.bar(names, height=values, width=0.9)
for bar in bars:
yval = bar.get_height()
plt.text(bar.get_x(), yval + .005, yval)
plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = True
plt.show()
Upvotes: 0