尝试使用 matplotlib [重复] 为图表上的每个点创建标签

问题描述 投票:0回答:1

我正在创建英国各县犯罪率与人口的散点图,我想让每个点都标有县名,这样我就可以将其可视化并查看每个县的相对安全性(使用 numpy、panda 和 matplotlib)

我还没有尝试过任何东西,但我知道你可以使用 annotate() 函数来获取数字

python csv matplotlib scatter-plot plot-annotations
1个回答
0
投票

您可以使用 matplotlib 中的

annotate()
函数。这是一个例子

import pandas as pd
import matplotlib.pyplot as plt

# Load data from CSV file into a Pandas DataFrame
data = pd.read_csv('uk_counties_data.csv')

# Create scatter plot
plt.scatter(data['population'], data['crime_rate'])

# Add labels to each point
for i in range(len(data)):
    plt.annotate(data['county'][i], xy=(data['population'][i], data['crime_rate'][i]))

# Set plot title and axis labels
plt.title('UK Counties Crime Rate vs Population')
plt.xlabel('Population')
plt.ylabel('Crime Rate')

# Display plot
plt.show()

我在这个 csv 文件中使用了一些数据:

county,population,crime_rate
Bedfordshire,664527,56.2
Berkshire,909902,47.5
Bristol,449300,74.9
Buckinghamshire,803577,47.8
Cambridgeshire,657751,49.1
Cheshire,1170194,71.6
Cornwall,568210,57.9
Cumbria,498888,60.5
Derbyshire,1065655,66.2
Devon,789908,57.4
Dorset,376426,52.8
Durham,526980,73.4
East Sussex,767415,55.9
Essex,1461700,68.2
Gloucestershire,626107,52.7
Greater London,8980170,85.6
Greater Manchester,2830000,96.2
Hampshire,1858000,52.4
Herefordshire,191031,46.2
Hertfordshire,1188077,50.1
Isle of Wight,141538,50.8
Kent,1661000,61.5
Lancashire,1461000,76.2
Leicestershire,715900,77.9
Lincolnshire,771349,61.1
Merseyside,1431000,97.4
Norfolk,899016,50.9
North Yorkshire,626964,56.3
Northamptonshire,723000,66.2
Northumberland,320000,57.9
Nottinghamshire,1152995,74.8
Oxfordshire,687927,54.6
Rutland,39895,37.4
Shropshire,320274,46.8
Somerset,560000,56.6
South Yorkshire,1400000,85.2
Staffordshire,1121253,71.3
Suffolk,758000,52.5
Surrey,1220000,49.9
Tyne and Wear,1336000,89.6
Warwickshire,557636,52.4
West Midlands,2900000,86.4
West Sussex,850000,48.7
West Yorkshire,2341000,82.1
Wiltshire,465000,43.2
Worcestershire,588000,52.8

并得到这个输出

result

© www.soinside.com 2019 - 2024. All rights reserved.