0

I would like to show the percentages of each bar on my horizontal bar chart but I am unsure how to do it. Also, ideally I would have the percentages at the ends of each bar if that were possible?

Here is my current script:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
%matplotlib inline

...
percentage = []

for i in top_ten_districts:
    percentage.append(int((i / total_ads)*100))

percentage = ['{}%'.format(x) for x in percentage]

top_ten_districts = active_ads.district.value_counts().head(10)
plt.barh(top_ten_districts.index, top_ten_districts)
plt.xlabel('num of ads')
plt.ylabel('county')
plt.title('TOP 10 DISTRICTS')
top_ten_districts

I would like to have the '%' sign after each percentage on the chart, however, when I execute the script, I get the following:

ConversionError: Failed to convert value(s) to axis units: '22%'

current chart:

enter image description here

LeoGER
  • 355
  • 1
  • 8
  • 1
    what values are in the x-axis? are those percentages? are you looking to show the % values inside of the plot close to the bar charts or simply on the axis? – emiljoj Apr 08 '20 at 12:50
  • Sorry for not being clear. On the x-axis are the number of ads (not percentages) and I would like the % values inside the plot for each bar. – LeoGER Apr 08 '20 at 12:55
  • 2
    first, you will have to calculate the % values and format them through '{:.2%}'.format for example. then you can follow the steps here to add those values from the list to your bars: https://stackoverflow.com/questions/30228069/how-to-display-the-value-of-the-bar-on-each-bar-with-pyplot-barh – emiljoj Apr 08 '20 at 12:57
  • Thank you @emiljoj for your help! Much appreciated. I now have the task of adding the '%' symbol, as explained in my edited question, I am having difficulties with that now. – LeoGER Apr 08 '20 at 18:14
  • 1
    see the example below for how to apply them to a list. let us know where exactly you are stuck: a = [0.1, 0.2, 0.3] b = [ '{:.2%}'.format(x) for x in a] print(b) – emiljoj Apr 09 '20 at 08:09
  • Thanks again for your comment! The output of `percentage = ['{}%'.format(x) for x in percentage]` is `['22%', '16%', '12%', '8%', '6%', '5%', '4%', '4%', '3%', '3%']`. The problem is putting it in my chart as I get the error message as above unfortunately. – LeoGER Apr 09 '20 at 08:24
  • 1
    Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/211270/discussion-between-emiljoj-and-leoger). – emiljoj Apr 09 '20 at 08:28

0 Answers0