有人可以帮我在每个单杠的顶部添加城市名称吗?我已经做了其他所有事情。只需要弄清楚。
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()
这是我为了获得条形图而编写的代码。我需要每个条上方标签的指导。
您必须将标签选项添加到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)