我使用cartopy创建了一个Open Street Map图:
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()
但这不起作用。
我猜我必须在某个地方的绘图命令中抛出一个变换参数?但我不确定如何去做。
谢谢!
答案 0 :(得分:2)
你对坐标转换的需要是正确的。这是一个带有结果图的工作代码。
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)
,其中
返回值xynps
是一个地图坐标数组。它有两列x和y,位于当前ax
使用的适当坐标系中。