首页 > 解决方案 > Python:如何将 shapefile 放置在一个绘图中的光栅文件顶部,然后将绘图保存为 Jpeg 文件格式

问题描述

我在网上搜索了三天后发布了这个问题,但没有成功。希望能在这里得到答案。请不要删除帖子,因为我在这里也没有找到答案。谢谢。

我有 2 个文件:

  1. 光栅图像文件(即,气温 2020-01-01.tif)
  2. 世界国家边界 shapefile((即 World_Countries_base_map.shp)

目标:我想在光栅文件的顶部绘制 shapefile,然后将绘图保存为 Jpeg 文件格式,最终得到这样的结果:

在此处输入图像描述

我是 Python 的新手,我使用 Spyder 准备了这个简单的代码:

# Import needed packages
import os
import rasterio
import matplotlib.pyplot as plt
import geopandas as gpd
import earthpy as et
from matplotlib import pyplot

## list all raster images in tiff format in the folder:
list_files = [f for f in 
       os.listdir('C:/Users/Desktop/Question/Raster_Air_temp') 
       if '.tif' in f]
print(list_files[1])  # checking the 1st file in the list

## reading the first tiff file:    
raster_image = rasterio.open(list_files[1])

## plot it
draft_output = pyplot.imshow(raster_image.read(1), cmap='jet')

## importing world shapefile
World_map = gpd.read_file('C:/Users/Desktop/Question/World_shapefile/World_Countries_base_map.shp')

# plot World shapefile
fig, ax = plt.subplots(figsize = (30,30))  # image size and quality can be controled by figsize
ax.set_title('The Glob Map', fontsize=50); 
World_map.plot(ax=ax, color='white', edgecolor='black')     # colors note at  https://matplotlib.org/tutorials/colors/colormaps.html
plt.show()

## Plot both World shapefile and raster image in one graph:

????  

在此处输入图像描述

但是,如上所示,此代码仅在控制台中为我生成了2 个单独的图。

问题:我怎样才能输入正确的代码????实现我的目标的代码部分(如上所述)?感谢所有评论和帮助。

在这里,我分享这两个文件是为了方便那些需要帮助的人。 从我的 Dropbox 下载文件

.

标签: pythonplotrastershapefilerasterio

解决方案


因为我无法访问您的数据,所以我使用来自 geopandas 的一些样本数据和随机 numpy ndarray 作为 tiff 代理来展示原理。

关键是用 rasterios rasterplot 显示 tiff,不要忘记设置 DEM 的范围!

在此处输入图像描述

import rasterio
import numpy as np
from rasterio import plot as rasterplot
import geopandas as gpd
from matplotlib import pyplot as plt


# this is how you'd open the raster dataset if you have one
#tiff = rasterio.open('example.tif')
#tiff_extent = [tiff.bounds[0], tiff.bounds[2], tiff.bounds[1], tiff.bounds[3]]

# i am making this array up
tiff_band_1 = np.random.randint(0, 10, size=(65, 64))
tiff_extent = [4159200.0, 4808100.0, 2828000.0, 3482600.0]

shapefile = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
shapefile = shapefile.to_crs('epsg:3035')
shapefile = shapefile[shapefile.name == 'Germany']

f, ax = plt.subplots()

# plot DEM
rasterplot.show(
    tiff_band_1,  # use tiff.read(1) with your data
    extent=tiff_extent,
    ax=ax,

)
# plot shapefiles
shapefile.plot(ax=ax, facecolor='w', edgecolor='k')
plt.show()

推荐阅读