0

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

enter image description here

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.

enter image description here

Dale K
  • 21,987
  • 13
  • 41
  • 69
Vikas
  • 189
  • 6

1 Answers1

0

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()
Rakesh
  • 78,594
  • 17
  • 67
  • 103