Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Change Bar Chart Values to Percentages (Matplotlib) [duplicate]

The code below generates a barchart with data labels above each bar (pictured at the bottom). Is there any way to make the ticks on the y axis into percentages (in this chart, would be 0%, 20%, etc.)?

I managed to get the data labels above each bar to depict percentages by concatenating the bar height with "%".

import numpy as np
import matplotlib.pyplot as plt

n_groups = 5

Zipf_Values = (100, 50, 33, 25, 20)
Test_Values = (97, 56, 35, 22, 19)

fig, ax = plt.subplots()

index = np.arange(n_groups)
bar_width = 0.35

rects1 = plt.bar(index, Zipf_Values, bar_width, color='g', 
    label='Zipf', alpha= 0.8)
rects2 = plt.bar(index + bar_width, Test_Values, bar_width, color='y', 
    label='Test Value', alpha= 0.8)

plt.xlabel('Word')
plt.ylabel('Frequency')
plt.title('Zipf\'s Law: Les Miserables')
plt.xticks(index + bar_width, ('The', 'Be', 'And', 'Of', 'A'))
plt.legend()

for rect in rects1:
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width()/2., 0.99*height,
            '%d' % int(height) + "%", ha='center', va='bottom')
for rect in rects2:
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width()/2., 0.99*height,
            '%d' % int(height) + "%", ha='center', va='bottom')

plt.tight_layout()
plt.show()

graph

like image 705
Cro2015 Avatar asked Mar 20 '16 17:03

Cro2015


1 Answers

You will want to specify a custom formatter for the y axis which will simply append the percent symbol to all of your existing labels.

from matplotlib.ticker import FuncFormatter

formatter = FuncFormatter(lambda y, pos: "%d%%" % (y))
ax.yaxis.set_major_formatter(formatter)

enter image description here

like image 190
Suever Avatar answered Sep 16 '22 19:09

Suever