0

Can anyone help me out to add the city name on the top of each horizontal bars? I have done everything else. Only need to figure out that.

import pandas as pd
import matplotlib.pyplot as plt
df1 = pd.read_csv("city_populations.csv")

#selecting particular columns
df = df1[['name','group','year','value']]
year = df1['year']
df = df.sort_values(by=['value'],ascending=False)

#selceting rows with year 2020
curr_year = 2020
#create a variable with true if year == curr_year
curr_population = df['year'] == curr_year
curr_population = df[curr_population]
print(curr_population)

#drawing the graph
fig,ax = plt.subplots(figsize = (10,8))
#to flip barh
values = curr_population[::-1]['group']
labels = []
clrs = []
for x in values:
    if x == "India":
        clrs.append("#adb0ff")
    elif x == "Europe":
        clrs.append("#ffb3ff")
    elif x == "Asia":
        clrs.append('#90d595')
    elif x == "Latin America":
        clrs.append("#e48381")
    elif x == "Middle East":
        clrs.append("#aafbff")
    elif x == "North America":
        clrs.append("#f7bb5f")
    else:
        clrs.append("#eafb50")
bar_plot = ax.barh(curr_population[::-1]['name'],curr_population[::-1]['value'],color = clrs)
plt.show()

This is the code I have written in order to get the bar graphs. I need guidance for the labels on top of each bars.

Savannah Madison
  • 575
  • 3
  • 8
  • 17
  • 1
    Does this answer your question? [Annotation of horizontal bar graphs in matplotlib](https://stackoverflow.com/questions/37789747/annotation-of-horizontal-bar-graphs-in-matplotlib) – Sheldore May 31 '20 at 12:08

1 Answers1

0

you have to add the label option to the barh method

enter code herebar_plot = ax.barh(curr_population[::-1]['name'],curr_population[::-1]['value'],color = clrs, label="test")

If you want to position a label more freely you can use something like this (taken from https://matplotlib.org/3.2.1/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py):

def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

autolabel(ax)
Andrea Pollini
  • 292
  • 4
  • 8