将栅格添加到ggmap基本地图:在ggplot2中设置alpha(透明度)并将颜色填充到inset_raster()

时间:2023-02-09 16:50:20

I want to plot a map with a raster overlaying a GoogleMaps base map in ggplot2. Therefore, I used get_map() and insert_raster() like this:

我想在ggplot2中绘制一个覆盖GoogleMaps基本地图的栅格的地图。因此,我使用了get_map()和insert_raster(),如下所示:

library(ggplot2)
library(ggmap)

bm <- ggmap(get_map(location = "Bangkok", maptype = "hybrid"))

bm + inset_raster(as.raster(r), xmin = r@extent[1], xmax = r@extent[2],
                  ymin = r@extent[3], ymax = r@extent[4])

Is there any possibility to set a alpha and change the fill color?

是否有可能设置alpha并更改填充颜色?

The result looks like this: 将栅格添加到ggmap基本地图:在ggplot2中设置alpha(透明度)并将颜色填充到inset_raster()

结果如下:

2 个解决方案

#1


9  

Even Faster without fortify:

read the original post below for further information

阅读下面的原始帖子了解更多信息

From this blog entry I found that we can use spatial polygons directly in ggplot::geom_polygon()

从这篇博文中我发现我们可以直接在ggplot :: geom_polygon()中使用空间多边形

r <- raster(system.file("external/test.grd", package="raster"))
# just to make it reproducible with ggmap we have to transform to wgs84
r <- projectRaster(r, crs = CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))

rtp <- rasterToPolygons(r)

bm <- ggmap(get_map(location = bbox(rtp), maptype = "hybrid", zoom = 13))
bm + 
  geom_polygon(data = rtp, 
               aes(x = long, y = lat, group = group, 
                   fill = rep(rtp$test, each = 5)), 
               size = 0, 
               alpha = 0.5)  + 
  scale_fill_gradientn("RasterValues", colors = topo.colors(255)) 

How to tackle plotting SPEED if you just need to visualize something

As described below, such plotting might become very slow with large numbers of pixels. Therefore, you might consider to reduce the number of pixels (which in most cases does not really decrease the amount of information in the map) before converting it to polygons. Therefore, raster::aggregate can be used to reduce the number of pixels to a reasonable amount.

如下所述,对于大量像素,这种绘图可能变得非常慢。因此,在将其转换为多边形之前,您可能会考虑减少像素数(在大多数情况下,这不会真正减少地图中的信息量)。因此,raster :: aggregate可用于将像素数减少到合理的数量。

The example shows how the number of pixels is decreased by an order of 4 (i.e. 2 * 2, horizontally * vertically). For further information see ?raster::aggregate.

该例子示出了像素数如何减少4的量级(即2 * 2,水平*垂直)。有关详细信息,请参阅?raster :: aggregate。

r <- aggregate(r, fact = 2)
#  afterwards continue with rasterToPolygons(r)...

Original Post:

After a while, I found a way to solve this problem. Converting the raster to polygons! This idea then basically was implemented after Marc Needham's blog post.

过了一会儿,我找到了解决这个问题的方法。将栅格转换为多边形!这个想法基本上是在Marc Needham的博客文章之后实现的。

Yet, there is one drawback: ggplot gets really slow with large numbers of polygons, which you will inevitably face. However, you can speed things up by plotting into a png() (or other) device.

然而,有一个缺点:ggplot因大量多边形而变得非常慢,你将不可避免地面对这些多边形。但是,您可以通过绘制到png()(或其他)设备来加快速度。


Here is a code example:

这是一个代码示例:

library(raster)
library(ggplot2)
library(ggmap)

r <- raster(....) # any raster you want to plot
rtp <- rasterToPolygons(r)
rtp@data$id <- 1:nrow(rtp@data)   # add id column for join

rtpFort <- fortify(rtp, data = rtp@data)
rtpFortMer <- merge(rtpFort, rtp@data, by.x = 'id', by.y = 'id')  # join data

bm <- ggmap(get_map(location = "Shanghai", maptype = "hybrid", zoom = 10))

bm + geom_polygon(data = rtpFortMer, 
                  aes(x = long, y = lat, group = group, fill = layer), 
                  alpha = 0.5, 
                  size = 0) +  ## size = 0 to remove the polygon outlines
     scale_fill_gradientn(colours = topo.colors(255))

This results in something like this:

这导致类似这样的事情:

将栅格添加到ggmap基本地图:在ggplot2中设置alpha(透明度)并将颜色填充到inset_raster()

#2


2  

just been looking into this myself. The issue i encountered was trying to overlay a ggmap output with a raster was the following error:

我自己一直在调查。我遇到的问题是尝试使用栅格覆盖ggmap输出时出现以下错误:

Error: geom_raster only works with Cartesian coordinates.

错误:geom_raster仅适用于笛卡尔坐标。

the work around to this issue is to use coord_cartesian() as follows:

解决这个问题的方法是使用coord_cartesian(),如下所示:

library(ggplot2)
library(ggmap)

bm <- ggmap(get_map(location = "Bangkok", maptype = "hybrid"))

bm <- bm + geom_raster(...) # insert your raster here

bm <- bm + coord_cartesian()

plot(bm)

I am not sure where your raster r is coming from. for this to work simply convert your raster r into a data frame and add the data according to the geom_raster() instructions, ensure the coordinates are in lat/long (i.e. same as the map).

我不确定你的光栅来自哪里。为此,只需将光栅r转换为数据帧并根据geom_raster()指令添加数据,确保坐标为纬度/经度(即与地图相同)。

To answer your question, through geom_raster() you can manipulate alpha and fill.

要回答你的问题,通过geom_raster()你可以操纵alpha和fill。

Hope this helps.

希望这可以帮助。

btw this work around was originally raised at this link: https://groups.google.com/forum/embed/#!topic/ggplot2/nqzBX22MeAQ

顺便说一句,这项工作最初是通过以下链接提出的:https://groups.google.com/forum/embed/#!topic /ggplot2 / nqzBX22MeAQ

#1


9  

Even Faster without fortify:

read the original post below for further information

阅读下面的原始帖子了解更多信息

From this blog entry I found that we can use spatial polygons directly in ggplot::geom_polygon()

从这篇博文中我发现我们可以直接在ggplot :: geom_polygon()中使用空间多边形

r <- raster(system.file("external/test.grd", package="raster"))
# just to make it reproducible with ggmap we have to transform to wgs84
r <- projectRaster(r, crs = CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))

rtp <- rasterToPolygons(r)

bm <- ggmap(get_map(location = bbox(rtp), maptype = "hybrid", zoom = 13))
bm + 
  geom_polygon(data = rtp, 
               aes(x = long, y = lat, group = group, 
                   fill = rep(rtp$test, each = 5)), 
               size = 0, 
               alpha = 0.5)  + 
  scale_fill_gradientn("RasterValues", colors = topo.colors(255)) 

How to tackle plotting SPEED if you just need to visualize something

As described below, such plotting might become very slow with large numbers of pixels. Therefore, you might consider to reduce the number of pixels (which in most cases does not really decrease the amount of information in the map) before converting it to polygons. Therefore, raster::aggregate can be used to reduce the number of pixels to a reasonable amount.

如下所述,对于大量像素,这种绘图可能变得非常慢。因此,在将其转换为多边形之前,您可能会考虑减少像素数(在大多数情况下,这不会真正减少地图中的信息量)。因此,raster :: aggregate可用于将像素数减少到合理的数量。

The example shows how the number of pixels is decreased by an order of 4 (i.e. 2 * 2, horizontally * vertically). For further information see ?raster::aggregate.

该例子示出了像素数如何减少4的量级(即2 * 2,水平*垂直)。有关详细信息,请参阅?raster :: aggregate。

r <- aggregate(r, fact = 2)
#  afterwards continue with rasterToPolygons(r)...

Original Post:

After a while, I found a way to solve this problem. Converting the raster to polygons! This idea then basically was implemented after Marc Needham's blog post.

过了一会儿,我找到了解决这个问题的方法。将栅格转换为多边形!这个想法基本上是在Marc Needham的博客文章之后实现的。

Yet, there is one drawback: ggplot gets really slow with large numbers of polygons, which you will inevitably face. However, you can speed things up by plotting into a png() (or other) device.

然而,有一个缺点:ggplot因大量多边形而变得非常慢,你将不可避免地面对这些多边形。但是,您可以通过绘制到png()(或其他)设备来加快速度。


Here is a code example:

这是一个代码示例:

library(raster)
library(ggplot2)
library(ggmap)

r <- raster(....) # any raster you want to plot
rtp <- rasterToPolygons(r)
rtp@data$id <- 1:nrow(rtp@data)   # add id column for join

rtpFort <- fortify(rtp, data = rtp@data)
rtpFortMer <- merge(rtpFort, rtp@data, by.x = 'id', by.y = 'id')  # join data

bm <- ggmap(get_map(location = "Shanghai", maptype = "hybrid", zoom = 10))

bm + geom_polygon(data = rtpFortMer, 
                  aes(x = long, y = lat, group = group, fill = layer), 
                  alpha = 0.5, 
                  size = 0) +  ## size = 0 to remove the polygon outlines
     scale_fill_gradientn(colours = topo.colors(255))

This results in something like this:

这导致类似这样的事情:

将栅格添加到ggmap基本地图:在ggplot2中设置alpha(透明度)并将颜色填充到inset_raster()

#2


2  

just been looking into this myself. The issue i encountered was trying to overlay a ggmap output with a raster was the following error:

我自己一直在调查。我遇到的问题是尝试使用栅格覆盖ggmap输出时出现以下错误:

Error: geom_raster only works with Cartesian coordinates.

错误:geom_raster仅适用于笛卡尔坐标。

the work around to this issue is to use coord_cartesian() as follows:

解决这个问题的方法是使用coord_cartesian(),如下所示:

library(ggplot2)
library(ggmap)

bm <- ggmap(get_map(location = "Bangkok", maptype = "hybrid"))

bm <- bm + geom_raster(...) # insert your raster here

bm <- bm + coord_cartesian()

plot(bm)

I am not sure where your raster r is coming from. for this to work simply convert your raster r into a data frame and add the data according to the geom_raster() instructions, ensure the coordinates are in lat/long (i.e. same as the map).

我不确定你的光栅来自哪里。为此,只需将光栅r转换为数据帧并根据geom_raster()指令添加数据,确保坐标为纬度/经度(即与地图相同)。

To answer your question, through geom_raster() you can manipulate alpha and fill.

要回答你的问题,通过geom_raster()你可以操纵alpha和fill。

Hope this helps.

希望这可以帮助。

btw this work around was originally raised at this link: https://groups.google.com/forum/embed/#!topic/ggplot2/nqzBX22MeAQ

顺便说一句,这项工作最初是通过以下链接提出的:https://groups.google.com/forum/embed/#!topic /ggplot2 / nqzBX22MeAQ