如何在matplotlib中的水平条形图上添加标签?

时间:2020-05-31 11:54:48

标签: python-3.x matplotlib graph

有人可以帮我在每个单杠的顶部添加城市名称吗? 我做了其他的一切。 只需弄清楚。

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()

这是我为了获得条形图而编写的代码。 我需要每个条上方标签的指导。

1 个答案:

答案 0 :(得分:0)

您必须将标签选项添加到barh方法中

enter code here bar_plot = ax.barh(curr_population [::-1] ['name'],curr_population [::-1] ['value'],color = clrs,label =“ test”)

如果您想更自由地放置标签,可以使用类似的方法(摘自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)
相关问题