如何在一个图中将矢量文件放置在栅格文件之上,然后以 JPEG 文件格式保存该图。

3

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

我有两个文件:

  1. 栅格图像文件(即,Air temperature 2020-01-01.tif)
  2. 世界国家边界形状文件(即,World_Countries_base_map.shp)

目标:我想在栅格文件上面绘制形状文件,然后将绘图保存为Jpeg文件格式,最终得到像这样的东西:

enter image description here

我在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:

????  

enter image description here

然而,这段代码对我来说只在控制台中产生了2个分离的图形,如上所示。

问题:我应该如何在代码的????部分输入正确的代码以达到我的目标(上述提到)? 感谢所有的评论和帮助。

在这里,我分享两个文件,以便那些想要帮助的人更容易地使用。 从我的Dropbox下载文件

.

1个回答

3

由于我无法访问您的数据,因此我将使用来自geopandas和随机numpy ndarray的示例数据来展示原理,作为tiff代理。

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

enter image description here

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.savefig('test.jpg')
plt.show()

1
它对我来说完美地运行了 但实际上它并没有保存图像,我认为可以使用一些matplotlib函数将绘图保存为图像。 - Talha Khan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接