使用ggplot中的两个渐变来分离土地和水域

时间:2019-04-25 00:13:46

标签: r ggplot2 maps geospatial

我正在尝试在地图上获得土地和水的两个单独的渐变。我能够得到水的坡度(第一个数字),而不是土地。

如何在此代码中为土地设置灰色渐变(类似于下面的图2)?

样本数据

library(marmap)
library(ggplot2)

greys <- c(grey(0.6), grey(0.93), grey(0.99))

# Get map data
bat <- getNOAA.bathy(-68, -51, -48, -39, res = 1, keep = TRUE)

使用水梯度生成图

autoplot(bat, geom = c("raster", "contour"), colour = "white", size = 0.1) + 
  scale_fill_gradientn(limits = c(-6600, 0), colors = c("steelblue4", "#C7E0FF")) +
  NULL

enter image description here

我尝试在scale_fill_gradientn中设置不同的限制,但运气不佳:

autoplot(bat, geom = c("raster", "contour"), colour = "white", size = 0.1) + 
  scale_fill_gradientn(limits = c(min(bat), max(bat)), 
                       colors = c("steelblue4", "#C7E0FF", greys)) +
  NULL

所需的输出(使用基本R的绘图功能完成)

plot(bat, image = TRUE, land = TRUE, lwd = 0.1, bpal = list(c(0, max(bat), greys), c(min(bat), 0, blues)))
plot(bat, lwd = 0.8, deep = 0, shallow = 0, step = 0, add = TRUE) # highlight coastline

enter image description here

2 个答案:

答案 0 :(得分:4)

使用cutscale_fill_manual的方法:

它比@ Z.Lin的答案(我个人会考虑)要复杂得多,但是这种方法可能会给您更多的控制权,geom_raster的绘制速度很快。

我已经手动完成了所有操作,但是您可以想象一个函数,该函数采用高程矢量和所需的多个中断点,然后将其切成一组类别中断点并进行适当调整标签。这是sp::spplot()默认对连续字段执行的操作,它使用nbreaks = 16。您需要强制零高度中断以区分陆地和海洋。

这是可以发展的总体思路。

# convert to raster, then data frame
library(raster)
d <- as.raster(bat)
d <- as.data.frame(d, xy=TRUE)

# upper and lower elevation bounds
z <- max(d$layer)
a <- min(d$layer)

# breaks and labels for color scale
brks <- c(a, 1000, 500, 0, -500, -1000, -2000, -3000, -4000, -5000, z)
labs <- c("> 1000", "500:1000", "0:500", "-500:0", "-1000:-500", "-2000:-1000",
          "-3000:-2000", "-4000:-3000", "-5000:-4000", "< -6514")
d$bin <- cut(d$layer, breaks = brks, labels = labs)
d <- d[!is.na(d$bin), ] # filter sneaky NA values

library(colormap)
gr   <- colormap(colormaps$greys, nshades = 10)[4:6]
bl   <- colormap(colormaps$velocity_blue, nshades = 13)[3:9]
cols <- c(bl, gr)

# plot
ggplot(d, aes(x, y, fill = bin)) +
  geom_raster() +
  scale_fill_manual(values = cols, limits = labs, labels = rev(labs)) +
  theme_minimal() +
  labs(fill = "Elevation (ft)")

enter image description here

答案 1 :(得分:2)

也许是这样?填充值的范围是通过检查summary(fortify.bathy(bat))的范围来获得的。{p>

z

plot

注意:我在这里使用autoplot(bat, geom = c("raster", "contour"), colour = "white", size = 0.1) + scale_fill_gradientn(values = scales::rescale(c(-6600, 0, 1, 1500)), colors = c("steelblue4", "#C7E0FF", "grey50", "grey80")) 作为灰度值的范围,但是您当然可以根据需要进行更改。