简体   繁体   English

Geopandas 在具有相同图例的 xarray 上绘制 shapefile

[英]Geopandas plot shapefile on xarray with same legend

I'm trying to create some maps of precipitation data (xarray) with a shapefile of the region of interest on top.我正在尝试创建一些降水数据地图(xarray),顶部有感兴趣区域的 shapefile。 However, when Python plots the figures, I get two seperate figures:但是,当 Python 绘制这些数字时,我得到两个单独的数字:

降水数据

感兴趣的区域

When I open the data in QGIS they do appear on top of each other, so the coordinate systems do check out.当我在 QGIS 中打开数据时,它们确实会出现在彼此之上,因此坐标系会检查出来。 Then I have an additional bonus question: I have to create multiple precipitation maps, on for a visual analysis it would be ideal if I could have the same legend (thus the same min/max for the colorbar) for each map.然后我有一个额外的奖励问题:我必须创建多个降水图,对于视觉分析,如果我可以为每张地图拥有相同的图例(因此颜色条的最小/最大值相同),那将是理想的。 Anyone an idea how to proceed further?有人知道如何进一步进行吗?

My code so far:到目前为止我的代码:

def chirps_to_map(input1, input2, title):

    projection = input1 + input2

    plt.figure(figsize=(9, 9))

    projection['pr'].plot()

    watershed.plot()

    plt.title(title)

    plt.show()

    plt.close()

    projection.to_netcdf(str(path)+str(title)+".nc")

    return projection

This is a case where it's simpler to use the Matplotlib object-oriented API.这是使用 Matplotlib 面向对象 API 更简单的情况。

A nice general workflow might be一个不错的通用工作流程可能是

fig, ax = plt.subplot()
gdf.plot(ax=ax)    # Plot the vector data on the subplot
raster.plot(ax=ax) # Plot the raster data on the same subplot

Example例子

First, we get some sample raster+vector data首先,我们得到一些样本栅格+矢量数据

import xarray as xr
import geopandas as gpd
import matplotlib.pyplot as plt

da = xr.tutorial.load_dataset('ROMS_example').zeta.isel(ocean_time=0)
gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
usa = gdf.loc[gdf['name'].eq('United States of America')]

Next, we plot both of the data on the same AxesSubplot接下来,我们在同一个AxesSubplot上绘制两个数据

fig, ax = plt.subplots(figsize=(15, 10))
da.plot.pcolormesh(x='lon_rho', y='lat_rho', ax=ax)
usa.plot(ax=ax, edgecolor='red', color='none')

# Focus on the raster extent
ax.set_xlim(-95, -87)
ax.set_ylim(26, 32)

在此处输入图像描述

Bonus: hvPlot way奖励: hvPlot方式

hvPlot provides a nice unified API for interactive plotting with pandas , xarray , and many other libraries, and might be of interest to people stumbling upon this answer. hvPlot为与pandasxarray和许多其他库的交互式绘图提供了一个很好的统一 API,并且可能对偶然发现这个答案的人感兴趣。

Plotting both vector and raster data is rather easy, simply use the * operator.绘制矢量和栅格数据相当容易,只需使用*运算符。

import hvplot.pandas
import hvplot.xarray

usa.hvplot(geo=True) * da.hvplot.quadmesh(x='lon_rho', y='lat_rho', geo=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM