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