Bar chart help in python with value label alignment in the center

Question:

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

Asked By: Vikas

||

Answers:

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

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.

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.