首页 > 解决方案 > OpenStreetMap 背景上的 Cartopy 热图

问题描述

我使用 cartopy 创建了一个开放街道地图图:

from __future__ import division
import numpy as np 
import matplotlib as mpl        
import matplotlib.pyplot as plt 
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt

request = cimgt.OSM()
extent = [-89, -88, 41, 42]

ax = plt.axes(projection=request.crs)
ax.set_extent(extent)

ax.add_image(request, 8)
plt.show()

在此处输入图像描述

现在我还有一个经度和纬度点列表。如何在街道地图上叠加这些经度和纬度点的热图?

我试过使用 hist2d,但这不起作用。

lons = (-88 --89)*np.random.random(100)+-89
lats = (41 - 42)*np.random.random(100)+42
ax.hist2d(lons,lats)
plt.show()

但这不起作用。

我猜我必须在某个地方的绘图命令中抛出一个转换参数?但我不确定如何去做。

谢谢!

标签: pythonheatmapcartopy

解决方案


您对坐标转换的需求是正确的。这是一个带有结果图的工作代码。

import numpy as np 
import matplotlib as mpl        
import matplotlib.pyplot as plt 
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt

request = cimgt.OSM()
fig, ax = plt.subplots(figsize=(10,16),
                       subplot_kw=dict(projection=request.crs))
extent = [-89, -88, 41, 42]  # (xmin, xmax, ymin, ymax)
ax.set_extent(extent)
ax.add_image(request, 8)

# generate (x, y) centering at (extent[0], extent[2])
x = extent[0] + np.random.randn(1000)
y = extent[2] + np.random.randn(1000)

# do coordinate conversion of (x,y)
xynps = ax.projection.transform_points(ccrs.Geodetic(), x, y)

# make a 2D histogram
h = ax.hist2d(xynps[:,0], xynps[:,1], bins=40, zorder=10, alpha=0.5)
#h: (counts, xedges, yedges, image)

cbar = plt.colorbar(h[3], ax=ax, shrink=0.45, format='%.1f')  # h[3]: image

plt.show()

结果图:在此处输入图像描述

编辑 1

ax用 被创建时plt.subplots(),它定义了一个特定的投影。在这种情况下,投影由关键字定义projection=request.crs。要在 上绘制某些东西ax,您必须使用它的坐标系。

坐标转换是用transform_points()语句中的函数完成的

xynps=ax.projection.transform_points(ccrs.Geodetic(), x, y)

在哪里

  • (x, y) 是(经度、纬度)值的列表,
  • ccrs.Geodetic() 表示值是 (long, lat) 以度为单位

返回值xynps是地图坐标数组。它有 2 列用于 x 和 y,它们位于 current 使用的适当坐标系中ax


推荐阅读