热点世界地图与Matplotlib

8
我正在尝试将热力图与我创建的世界地图结合起来。我得到了一个包含三列的CSV文件。第一列包含国家的名称,第二列和第三列分别包含纬度和经度。现在我编写了一个类,根据这些坐标在世界地图上绘制点。这个功能很好,但现在我想要一个热力图,因为只有几个点时一切看起来很好,但是我将拥有许多点。因此,根据国家中的点数和指定的边界,应该实现热力图。
import csv

class toMap:

    def setMap(self):
        filename = 'log.csv'
        lats, lons = [], []

        with open(filename) as f:
            reader = csv.reader(f)

            next(reader)

            for row in reader:
                lats.append(float(row[1]))
                lons.append(float(row[2]))

        from mpl_toolkits.basemap import Basemap
        import matplotlib.pyplot as plt
        import numpy as np

        map = Basemap(projection='robin', resolution='l', area_thresh=1000.0,
                      lat_0=0, lon_0=-130)
        map.drawcoastlines()
        map.drawcountries()
        map.fillcontinents(color='gray')
        #map.bluemarble()
        #map.drawmapboundary()
        map.drawmeridians(np.arange(0, 360, 30))
        map.drawparallels(np.arange(-90, 90, 30))

        x, y = map(lons, lats)
        map.plot(x, y, 'ro', markersize=3)

        plt.show()

def main():
    m = toMap()
    m.setMap()

这是一个 CSV 文件的示例:

这是一个 CSV 文件的示例:

Vietnam,10.35,106.35
United States,30.3037,-97.7696
Colombia,4.6,-74.0833
China,35.0,105.0
Indonesia,-5.0,120.0
United States,38.0,-97.0
United States,41.7511,-88.1462
Bosnia and Herzegovina,43.85,18.3833
United States,33.4549,-112.0777

我很想看看你如何构建CSV文件,这看起来非常有趣!你目前的输出是什么?我猜你发布的图片是通用的吗? - Phorce
你在上面看到的输出是我想要实现的,它不是我上面编写的代码的任何一个输出。应该长成这样的某种形式。我将编辑我的帖子并向您展示我的CSV文件的样子以及代码当前的输出。 - user3305988
我可能在这里非常愚蠢...但是,如果您在CSV文件中提供了x,y坐标,那么您肯定可以使用热图在这些坐标上绘制吧?我相当确定我已经看到过类似于您所提出的想法的热图;但我会在午餐时间查找并看看是否能找到这些示例。 - Phorce
你可以使用cartopy来实现你想要的功能。 请参考这里:https://dev59.com/1mYr5IYBdhLWcg3wxNC8 如果要根据某个数字选择国家的颜色,请使用0到1之间的值调用matplotlib colormap实例。这里有一个示例:https://dev59.com/XmLVa4cB1Zd3GeqPu0qQ - carla
1个回答

7

根据我上面的评论逻辑,我对你的代码进行了一些更改,以获得你想要的地图类型。

我的解决方案使用了cartopy库

所以这是你的代码,带有我的更改(和注释):

import csv

class toMap:

def setMap(self):
    # --- Save Countries, Latitudes and Longitudes ---
    filename = 'log.csv'
    pais, lats, lons = [], [], []

    with open(filename) as f:
        reader = csv.reader(f)

        next(reader)

        for row in reader:
            pais.append(str(row[0]))
            lats.append(float(row[1]))
            lons.append(float(row[2]))

    #count the number of times a country is in the list
    unique_pais = set(pais)
    unique_pais = list(unique_pais)

    c_numero = []

    for p in unique_pais:
        c_numero.append(pais.count(p))
        print p, pais.count(p)

    maximo = max(c_numero)

    # --- Build Map ---
    import cartopy.crs as ccrs
    import cartopy.io.shapereader as shpreader
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import numpy as np

    cmap = mpl.cm.Blues

    # --- Using the shapereader ---
    test = 0
    shapename = 'admin_0_countries'
    countries_shp = shpreader.natural_earth(resolution='110m',
                                            category='cultural', name=shapename)

    ax = plt.axes(projection=ccrs.Robinson())
    for country in shpreader.Reader(countries_shp).records():
        nome = country.attributes['name_long']
        if nome in unique_pais:
            i = unique_pais.index(nome)
            numero = c_numero[i]
            ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                              facecolor=cmap(numero / float(maximo), 1),
                              label=nome)
            test = test + 1

        else:
            ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                              facecolor='#FAFAFA',
                              label=nome)

    if test != len(unique_pais):
        print "check the way you are writting your country names!"

    plt.show()


def main():
    m = toMap()
    m.setMap()

我根据你的逻辑制作了一个自定义的带有一些国家的log.csv文件,这是我的地图:enter image description here

(我使用了蓝调色板,并且比例尺的最大值是根据你的csv文件中每个国家出现次数的最大值定义的。)

根据你在修改问题之前提供的示例图片,我认为这正是你想要的!


1
正是我所需要的,谢谢。另外,在我的示例中加入像上面那样的网格 **gl =ax.gridlines(draw_labels=False)**。只是为了完整起见 ;) - user3305988

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接