[英]Plotting naturalearth RasterLayer with natural colors using R and ggplot2
I am trying to create a map of some parts of South America using naturalearthdata.我正在尝试使用自然地球数据创建南美洲某些地区的地图。 It is important for me that I create a ggplot2 object, so I can further modify and combine the plot with geom_sf and geom_points.
创建 ggplot2 对象对我来说很重要,因此我可以进一步修改绘图并将其与 geom_sf 和 geom_points 组合。 THe last part, which I thought would be most challenging, is already done.
我认为最具挑战性的最后一部分已经完成。
My main problem right now is that the raster-object is colored as if the integer value were an intensity.我现在的主要问题是光栅对象的颜色就好像整数值是强度一样。 However, I would like the color to be as in the source: https://www.naturalearthdata.com/downloads/10m-natural-earth-1/10m-natural-earth-1-with-shaded-relief-water-and-drainages/
但是,我希望颜色与来源相同: https : //www.naturalearthdata.com/downloads/10m-natural-earth-1/10m-natural-earth-1-with-shaded-relief-water-和-排水系统/
I use the following code:我使用以下代码:
library(tidyverse)
library(raster)
hills <- raster("./map_data/NE1_LR_LC_SR_W_DR.tif")
# for the larger dataframe, my RStudio keeps crashing
hills_df <- as.data.frame(hills, xy = T) %>%
filter(x >= -90) %>% filter(x <= -55) %>% filter(y <= 5) %>% filter(y >= -30)
ggplot(data = hills_df) +
geom_raster(aes(x=x, y=y,fill=NE1_LR_LC_SR_W_DR))
The problem is that the data frame only has another column which is an integer value.问题是数据框只有另一列是整数值。 By setting the aesthetics to
fill=value
, this integer gets mapped as magnitude.通过将美学设置为
fill=value
,这个整数被映射为大小。 How can I implement the natural coloring as in the source?如何实现源中的自然着色?
Best, Tarotis最好的,塔罗蒂斯
One way to achieve this is making a data.frame
with coordinates of each cell of the rasterStack
and values of the three layers combined via rgb
, refer to this blog post .实现此目的的一种方法是使用
data.frame
的每个单元格的rasterStack
以及通过rgb
组合的三层值制作一个data.frame
,请参阅此博客文章。
However, geom_tile
and even geom_raster
appear to be very slow when as few as tens of thousands of pixels are involved.然而,当涉及少至数万个像素时,
geom_tile
甚至geom_raster
似乎非常慢。 I use the following workaround:我使用以下解决方法:
rasterStack
rasterStack
创建一个 3D 矩阵rgb
function (like explained in this SO answer )rgb
函数将其折叠为二维(就像在这个 SO 答案中解释的那样)annotate_raster
annotate_raster
将 RGB 值矩阵引入 ggplot The code can be as follows:代码可以如下:
library(tidyverse)
library(raster)
natearth_map <-
raster::stack('./map_data/NE1_LR_LC_SR_W_DR.tif') %>% # import tiff as rasterStack
crop(extent(-90, -55, -30, 5)) %>% # subset to desired extent
as.array %>% # convert to 3D array
`/`(255) %>% # switch to proportions to meet rgb() requirements
apply(c(1, 2), function(x) rgb(matrix(x, ncol = 3))) %>% # collapse layers to RGB colors
annotation_raster(-90, -55, -30, 5) # make it a ggplot object
Then you can add it to your ggplot like this.然后你可以像这样将它添加到你的 ggplot 中。
ggplot(data, aes(x, y)) + natearth_map + geom_point()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.