我有一个类似以下的数据集:
import pandas as pd
import numpy as np
df = pd.DataFrame({
# some ways to create random data
'Name of City':np.random.choice(["City A", 'City B', 'City C', "City D", "City E", "City F", "City G"], 22),
'Name of Country':np.random.choice(["Country A", "Country B", "Country C"], 22),
'lat':np.random.choice([-41, -20, 1, 19, 34, 66, 81], 22),
'lon': np.random.choice([- 10, 10, 4, 1, -20, 60, 0], 22)
})
其中lat / lon表示坐标,城市名称表示所属城市。
我想使用坐标在世界地图上绘制城市坐标-点的大小取决于我的数据集中该城市的出现次数,但不知道如何做到最好。
基于此代码
for idx, row in df.iterrows():
x, y = row[['lon','lat']]
plt.annotate(
str(idx),
xy = (x, y), xytext = (-20, 20),
textcoords = 'offset points', ha = 'right', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
plt.show()
我设法以某种方式绘制了点,但无法弄清楚如何将其放置在地图上。有人可以指出我正确的方向吗?
非常感谢!
答案 0 :(得分:2)
我不清楚您的坐标应如何与您的城市名称相关联,但假设每次提及某个城市时都应使用相同的坐标对。在此基础上,我稍微自由了一些,如何生成一个满足这些要求的数据库以及如何从中提取数据。其余的或多或少都可以使用Basemap
:
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits import basemap
cities = pd.DataFrame({
'city': ["City A", 'City B', 'City C', "City D", "City E", "City F", "City G"],
'lat': [-41, -20, 1, 19, 34, 66, 81],
'lon': [- 10, 10, 4, 1, -20, 60, 0],
})
print(cities)
choices = np.random.choice(range(len(cities.lat)),22)
print(choices)
counts = np.array([list(choices).count(i) for i in range(len(cities.lat))])
print(counts)
fig, ax = plt.subplots()
bmap = basemap.Basemap(ax = ax)
bmap.drawcountries()
bmap.drawcoastlines()
x,y = bmap(cities.lon, cities.lat)
ax.scatter(x, y, s=(2*counts)**2, c='r', label=cities.city)
for idx, row in cities.iterrows():
x, y = bmap(*row[['lon','lat']])
plt.annotate(
str(idx),
xy = (x, y), xytext = (-20, 20),
textcoords = 'offset points', ha = 'right', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
plt.show()
生成的图像如下所示: