虽然可以通过以下任一方式绘制地图:
crs = area_def.to_cartopy_crs()
ax = plt.axes(projection=crs)
ax.background_img(name='BM')
plt.imshow(result, transform=crs, extent=crs.bounds, origin='upper', cmap='RdBu_r')
或
sst = dataset.variables['sst'][0, :, :]
lats = dataset.variables['lat'][:]
lons = dataset.variables['lon'][:]
ax = plt.axes(projection=ccrs.PlateCarree())
plt.contourf(lons, lats, sst, 60,
transform=ccrs.PlateCarree())
第一个需要一个 crs 对象。第二个仅适用于填充等高线图。 有没有办法获得包含三个数组、数据、纬度和经度的 imshow 地图图。
并非如此,我认为这没有意义。使用
imshow
时,您可以绘制任何您想要的二维数组,无论它是什么投影,或者它是否实际上是地理数据。将其与其他数据组合还需要使用您正在绘制的数组的坐标来指定正确的范围。
由于
imshow
需要一个规则数组(网格),因此没有必要为每个元素指定坐标,只需外部范围就足够了。如果这就是您想做的全部,则不需要使用 Cartopy,只需 Matplotlib 就足够了。
但是一旦您想要在不同的投影中混合其他地理元素、国家边界、经纬度网格线或其他数据,您可能会想要使用 Cartopy,因为它非常方便。
绘制不规则网格时也是如此,这时像
contourf
或pcolormesh
这样的方法就变得有用了。这些确实需要每个元素的明确坐标。与 imshow
类似,这些方法不需要 Cartopy 和指定的投影。当您想要混合其他地理数据(可能在另一个投影中)时,这非常方便。
通过确保绘制的所有数据共享相同的投影,您始终可以避免对 Cartopy(或底图等)的依赖。但在大多数情况下,这并不值得付出努力,至少对我个人来说是这样。
虽然你的标签中有
cartopy
,但我认为你想要实现的目标可以通过geopandas来解决。重要的概念是在图中绘制点时使用相同的 CRS,以便所有信息对齐。
让我们看一个简单的例子
import geopandas
from matplotlib import pyplot as plt
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'))
ax = world.plot(color='white', edgecolor='black')
cities.plot(ax=ax, marker='o', color='red', markersize=5)
plt.show()
注意:由于我们想在同一张地图上绘制城市,因此我们使用相同的图形轴
ax
。另请注意,world
和 cities
具有相同的 CRS
。
你可以通过这样做看到这一点
print(world.crs, cities.crs)
epsg:4326 epsg:4326
两者都返回
epsg:4326
,所以相同CRS
。
现在,您有一组新的点要添加到绘图中。 让我们创建一些随机点。
from shapely import Point
import numpy as np
np.random.seed(1)
my_points = geopandas.GeoDataFrame(
geometry=[Point(x, y) for x, y in zip(
np.random.uniform(low=30, high=40, size=10),
np.random.uniform(low=-30, high=-10, size=10)
)], crs=world.crs
)
在这里,我们在东经 lon [30, 40] 和南经 lat [10, 30] 之间创建随机点。 请注意,我正在复制
crs
的 world
,因为它是 epsg:4326
。
如果是其他东西,我们会用
my_points
初始化 crs='epsg:4326'
,然后将 my_points
翻译为 world.crs
,如下
my_points.to_crs(crs=world.crs, inplace=True)
最后我们可以在相同的轴上绘图
my_points.plot(ax=ax, marker='s', color='g', markersize=10)
欲了解更多,请访问此页面
来自:
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(1,1,1, projection=crs.Robinson())
ax.set_global()
ax.add_feature(cfeature.COASTLINE, edgecolor="tomato")
ax.add_feature(cfeature.BORDERS, edgecolor="tomato")
ax.gridlines()
plt.scatter(x=starbucks_locations.Longitude, y=starbucks_locations.Latitude,
color="dodgerblue",
s=1,
alpha=0.5,
transform=crs.PlateCarree()) ## Important
plt.show()
我还使用marker=“s”和s=5来获得大方形标记,这样它就会显示为图像。