简体   繁体   English

我无法使用 matplotlib 在图表上标记数据点

[英]I am unable to label the data points on the graph using matplotlib

This is the code that I have been writing, but unable to add labels to the data points.这是我一直在编写的代码,但无法为数据点添加标签。 Have tried multiple ways but getting error one after the other!!尝试了多种方法,但一个接一个地出错! The data set in 9th line: 'country' is to be used as labelling.第 9 行中的数据集:“国家”将用作标签。 I want to label the 1st and last data point.我想标记第一个和最后一个数据点。 Please Help!请帮忙!

```python
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

data = pd.read_csv('happy_income1.csv')
happy = data['happyScore']
satis = data['avg_satisfaction']
country = data['country']

# Zapping 2 arrays together
satis_happy = np.column_stack((satis,happy))

# Sorting
data.sort_values('avg_satisfaction', inplace=True) #Sorting Data Column

# Filtering
satisfied = data[data['avg_satisfaction']>4] #Making Section as per requirement
print(satisfied)

# Making clusters as required
k_res = KMeans(n_clusters=3).fit(satis_happy)
cluster = k_res.cluster_centers_
print(cluster)

# Plotting
fig, week4 = plt.subplots()
week4.scatter(x=happy, y=satis)
week4.scatter(x=cluster[:,0], y=cluster[:,1], s=9999, alpha=0.25)
week4.set_xlabel('Happiness')
week4.set_ylabel('Satisfaction')
week4.set_title('Happiness versus Satisfaction')

# Labelling
# ----------------------------------------------

plt.show()
```

CSV File Link: Click Here CSV 文件链接: 点击这里

You can add these two additional lines after plotting the scatter plots.您可以在绘制散点图后添加这两条附加线。 They will add the text to the first and last entries.他们会将文本添加到第一个和最后一个条目。 You can do additional things like background box, etc. if required.如果需要,您可以执行其他操作,例如背景框等。 You can check matplotlib documentation and examples here您可以在此处查看 matplotlib 文档和示例

offset=0.05
week4.annotate(country[0], (happy[0]+offset, satis[0]+offset), color='red', weight='bold')
week4.annotate(country.iat[-1], (happy.iat[-1]+offset, satis.iat[-1]+offset), color='blue', weight='bold')

Output graph输出图

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM