我正在尝试在地图上获得土地和水的两个单独的渐变。我能够得到水的坡度(第一个数字),而不是土地。
如何在此代码中为土地设置灰色渐变(类似于下面的图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
我尝试在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
答案 0 :(得分:4)
cut
和scale_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)")
答案 1 :(得分:2)