rio.plot.show如何显示colorbar?

8
使用rio.plot.show后如何添加色条? 我尝试过很多方法,但是出现了各种错误。
以下是我尝试的其中一种方式:
fig, ax = plt.subplots(figsize = (16, 16))

retted = rio.plot.show(ds, ax=ax, cmap='Greys_r')  

fig.colorbar(retted, ax=ax)
plt.title("Original")
plt.show()

出现了错误:AttributeError: 'AxesSubplot' 对象没有 'get_array' 属性


3
我猜解决方法是用 i = ax.imshow(ds, cmap='Greys_r') 绘制图像,然后用rio绘图覆盖它,最后添加颜色条 plt.colorbar(i) - david
4个回答

9

我按照上面david建议的做法,结果成功了!

fig, ax = plt.subplots(figsize=(5, 5))

# use imshow so that we have something to map the colorbar to
image_hidden = ax.imshow(image_data, 
                         cmap='Greys', 
                         vmin=-30, 
                         vmax=30)

# plot on the same axis with rio.plot.show
image = rio.plot.show(image_data, 
                      transform=src.transform, 
                      ax=ax, 
                      cmap='Greys', 
                      vmin=-30, 
                      vmax=30)

# add colorbar using the now hidden image
fig.colorbar(image_hidden, ax=ax)

2
排版很好,而且你还给了David以功劳。作为你的第一个回答,做得非常好。目前我没有时间测试你的解决方案,所以无法评论其正确性。 - Marjeta
1
@Marjeta,我和 OP 有同样的问题。我测试了这个答案,它可以正常工作。根据这个页面 https://sigon.gitlab.io/post/2018-11-08-plot-raster-nodata-values/,我认为 colorbar 是默认添加的... - Alessandro Jacopson
1
我在尝试不同的方法时偶然发现了这个解决方案。在探索是否有更优雅的解决方案时,偶然发现了这个答案。目前似乎这是唯一的方法。 - DotPi
1
请注意,如果光栅图像被旋转,则当前代码将在非旋转(且不再隐藏)的图像上绘制旋转后的图像。我曾遇到这个问题,并通过添加 image_hidden.set_visible(False) 解决了它。 - WaterFox

6
plt.imshow() 和 rasterio.plot.show() 返回的对象不同。plt.colorbar() 需要一个可映射对象,所以它会感到困惑。因为 rasterio 绘图是 matplotlib 的包装器,所以我认为最直接的方法是提供底层对象 maptlotlib 所需的。
retted = rio.plot.show(ds, ax=ax, cmap='Greys_r')
im = retted.get_images()[0]
fig.colorbar(im, ax=ax)

1

我同意这个解决方案,但我想补充一点,如果你和我一样,通常会有一个rasterio datasetreader对象(使用rasterio.open读取地理参考栅格数据的结果),而不仅仅是原始的numpy数组。所以在rasterio v1.1.8中,我需要额外的步骤从datasetreader对象中提取numpy数组。例如,对于单波段:

dem = rasterio.open("GIS/anaPlotDEM.tif")
fig, ax = plt.subplots(figsize=(10,10))
image_hidden = ax.imshow(dem.read()[0])
fig.colorbar(image_hidden, ax=ax)
rasterio.plot.show(dem, ax=ax)

(我想把这个作为评论添加,但是没有足够的声望点数)


0
如果数据使用不同的坐标系。当您添加隐藏图像时,您更改了x轴和y轴。添加以下代码将解决问题:
# set the plot boundary to data.bounds
ax.set_xlim(data.bounds.left, data.bounds.right)
ax.set_ylim(data.bounds.bottom, data.bounds.top)

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