底图 - 根据坐标在地图上绘制点;点大小=出现次数

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

我有一个如下数据集:

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()

我设法以某种方式绘制点,但无法弄清楚如何将它们放在地图上。有人能指出我正确的方向吗?

提前谢谢了!

python-3.x matplotlib-basemap
1个回答
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()

生成的图像看起来像这样:

enter image description here

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