Skip to content Skip to sidebar Skip to footer

How Do I Add Percentage In Horizontal Bar Chart?

I have the following code, which creates a horizontal bar chart: data = pandas.read_csv('C:/py/matplotlib/02-BarCharts/data.csv') responders_id = data['Responder_id'] langs_worked_

Solution 1:

Here is one way to do it. I chose some sample data. The idea is

  • Create new y-tick labels by adding the name of the language and the percentage
  • Assign these modified labels on the y-axis
  • Hide the frame and the x-axis of the figure together with the y-axis ticks

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

total = 90000
langs = ['C', 'C++', 'Java', 'Python']
langs_users_num = np.array([32000, 40000, 50000, 60000])

percent = langs_users_num/total*100

new_labels = [i+'  {:.2f}%'.format(j) for i, j in zip(langs, percent)]

plt.barh(langs, langs_users_num, color='lightskyblue', edgecolor='blue')
plt.yticks(range(len(langs)), new_labels)
plt.tight_layout()

for spine in ax.spines.values():
    spine.set_visible(False)

ax.axes.get_xaxis().set_visible(False)
ax.tick_params(axis="y", left=False)
plt.show()

enter image description here


Post a Comment for "How Do I Add Percentage In Horizontal Bar Chart?"