Python 从dataframe向matplotlib图表添加标签失败
我在matplotlib中创建了一个图表,它是子图,根据另一列为每个点提供颜色: 我想从另一个名为city的列中为每个点添加标签,因此在每个点旁边,它将告诉数据来自哪个城市 我发现可以使用我在这里找到的函数:Python 从dataframe向matplotlib图表添加标签失败,python,matplotlib,plot,label,Python,Matplotlib,Plot,Label,我在matplotlib中创建了一个图表,它是子图,根据另一列为每个点提供颜色: 我想从另一个名为city的列中为每个点添加标签,因此在每个点旁边,它将告诉数据来自哪个城市 我发现可以使用我在这里找到的函数: #PLOT fig = plt.figure(figsize = (12,8)) ax = fig.add_subplot(1,1,1) ax.set_xlabel('population', fontsize = 15) ax.set_ylabel('PM 2.5', fonts
#PLOT
fig = plt.figure(figsize = (12,8))
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('population', fontsize = 15)
ax.set_ylabel('PM 2.5', fontsize = 15)
ax.set_title('Population vs population', fontsize = 20)
ax.annotation
##color the points according to the cluster analysis result
targets = df.pop_ndvi_pm_km6.unique()
colors = ['darkgreen', 'b', 'orange','purple','r','y']
for target, color in zip(targets,colors):
#goes to line. and check of 40,70 and 100 are true or false, 3 times total, and if true gives the color.
indicesToKeep = df['pop_ndvi_pm_km6'] == target
ax.scatter(df.loc[indicesToKeep, 'population']
, df.loc[indicesToKeep, 'pm 2.5']
, c = color
, s = 100)
ax.legend(targets)
ax.grid()
######The functuion I have tried to add the labels to the points########
def label_point(x, y, val, ax):
a = pd.concat({'x': x, 'y': y, 'val': val}, axis=1)
for i, point in a.iterrows():
ax.text(point['x'], point['y'], str(point['val']))
label_point(df['population'], df['PM 2.5'], df['City'], ax)
draw()
但是我得到了错误
AttributeError:“AxeSubPlot”对象没有属性“annotation”
我的最终目标:根据数据来源的城市名称为每个点添加标签。这是否回答了您的问题?我试过了,但也没有成功:(只是删除
ax.annotation
和draw()
,对我来说很有效。