python - 使用 MatPlotLib 的热力世界地图

标签 python matplotlib plot maps

<分区>

我正在尝试将热图与我创建的世界地图结合起来。我得到的是一个包含 3 列的 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 文件的示例:

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

最佳答案

按照我上面评论中的相同逻辑,我对您的代码进行了一些更改以获得您想要的 map 类型。

我的解决方案使用 cartopy library .

这是你的代码,加上我的更改(和评论):

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 文件,这是我的 map : enter image description here

(我使用了 Blues 颜色图,并且比例的最大值是根据一个国家在您的 csv 文件中出现的最大次数来定义的。)

根据您在编辑问题之前的示例图片,我认为这正是您想要的!

关于python - 使用 MatPlotLib 的热力世界地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22684730/

相关文章:

matlab - 如何在 Matlab 中绘制带通滤波器传递函数的频率响应?

python - matplotlib FigureCanvasQTAgg : slow rotation and grid overlaping surface on QWidget

python - flask 邮件(python): Running out of application context error

python - SysLogHandler 消息在远程服务器上集中在一行中

python - 在 python 中使用 matplotlib 创建 3D 曲面图

python - 如果值超过 matplotlib 中的 xlim,如何环绕绘图

python - y 轴的最小值未应用于 matplotlib vlines 图中

matlab - 如何创建曲面图的一部分来创建一条线? (Matlab)

java - Java ZonedDateTime.toInstant()行为

r - 并排绘制 gList