csv 尝试使用matplotlib [duplicate]为图上的每个点创建标签

9vw9lbht  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(88)

此问题已在此处有答案

Scatter plot with different text at each data point(9个回答)
How to annotate points in a scatterplot based on a pandas column(1个答案)
Annotating scatterplot points with DF column text Matplotlib(1个答案)
How to add hovering annotations to a plot(12个答案)
Annotate data points while plotting from Pandas DataFrame(4个答案)
6小时前关闭
我正在创建一个英国县犯罪率与人口的散点图,我希望每个点都标有县的名称,这样我就可以可视化它并查看每个县的相对安全性(使用numpy,panda和matplotlib)
我还没有尝试任何东西,但我知道你可以使用annotate()函数来获得数字

polkgigr

polkgigr1#

你可以使用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

相关问题