python-3.x - 如何使值小于 0.2 的像素透明,以便在 Python 中可以看到背景中的底图?
问题描述
我正在插入点数据以在 for 循环中生成动态洪水淹没图。这会在每次迭代中生成洪水地图,其中像素值显示水存在的概率。但是,我无法使干像素(值 < 0.2)透明,因此添加时可以看到底图。
最初,我创建了一个预测概率的地理数据框。然后使用 rasterio 库生成光栅文件,使用条件 (<0.2 = np.nan) 设置干像素。我的代码是:
geom = [Point(xy) for xy in zip(df.X, df.Y)]
crs = {'init': 'epsg:27700'}
gdf = geopandas.GeoDataFrame(df, crs=crs, geometry=geom)
###Rasterization
#Set up filenames
rst_fn = 'dem_9m_study_area.asc' #template raster
out_fn = 'Raster.tif'
rst = rasterio.open(rst_fn)
#copy and update the metadata from the input raster for the output
meta = rst.meta.copy()
meta.update(compress='lzw')
with rasterio.open(out_fn, 'w', **meta) as out:
out_arr = out.read(1)
shapes = ((geom,value) for geom, value in zip(gdf.geometry, gdf.Prob))
burned = features.rasterize(shapes=shapes, fill=0, out=out_arr, transform=out.transform)
burned[burned < 0.2] = np.nan
out.write_band(1, burned)
现在我想导入保存的栅格并将其绘制在同样位于同一坐标 (EPSG:27700) 中的背景栅格上,并显示颜色条。
我试过这个:
plt.figure(num=None, figsize=(10, 8), dpi=80, facecolor='w', edgecolor='k')
plt.imshow(burned, cmap='Blues')
plt.colorbar()
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Flood Extent: T=%i h'%op)
尽管 x 和 y 坐标显示不正确,但没有背景也可以正常工作。但是如果我将它添加到上面的代码中就不起作用:
bmap = rasterio.open("background_upton.tif") #import basemap
src = bmap.read(1)
plt.imshow(src, cmap = 'pink')
我还尝试了“向绘图添加背景地图”中描述的方法:https ://geopandas.readthedocs.io/en/latest/gallery/plotting_basemap_background.html
但这似乎并不能解决问题。如果我能得到一些解决问题的建议,那就太好了。 我想使用此背景图像覆盖范围图
解决方案
尝试为您的颜色图设置最小值,然后将低于最小值的值指定为完全透明。
我将创建一个值为 1 或 2 的示例数组。
import numpy as np
import matplotlib.pyplot as plt
arr = np.ones([64,64])
arr[0:32] = 2
plt.imshow(arr, cmap='viridis')
plt.colorbar()
现在假设在这种情况下我们希望 1(紫色)的值是透明的。我们可以通过设置颜色映射下限然后指定如何映射低于限制的值来做到这一点:
cmap = plt.get_cmap('viridis')
cmap.set_under('k', alpha=0)
plt.imshow(arr, cmap=cmap, vmin=1.5)
plt.colorbar()
“k”实际上是黑色的,但alpha=0
使其透明
推荐阅读
- google-data-studio - Google 数据无法访问嵌入网址
- java - 为 LIst 中的元素创建子序列
- c# - 任务、IsReminderSet 和 task.ReminderDueDate 上的 ServiceObjectPropertyException
- vue.js - 如何在不影响其他行的情况下删除该行
- javascript - 选择禁用选项标签的不同方法
- python - 如何从字符串的开头删除特定字符
- reactjs - 从科尔多瓦迁移到本机反应时如何保持用户登录
- wso2 - 在 WSO2 API 中隐藏或删除 XML 响应中的某些数据
- javascript - React - 在对象之间定义更大的字符串
- c# - 属性在不同的操作系统中不起作用,函数抛出异常(System.Management.ManagementException:未找到)