I'm trying to set breaks for elevation when plotting raster data but it seems to only be using two of my colors instead of the full set. I have elevation values from -5497 to 1413 and want to use light to dark blue color gradient for negative elevations (water) and grey to black colors for positive elevation (land).
Acquired data from NOAA via marmap package
# RASTER BATHY DATA
# From NOAA using marmap package
library(marmap)
library(oce)
Library(raster)
library(ggplot2)
bathy <- getNOAA.bathy(-80, -70, 40, 32, resolution = 1,
keep = FALSE, antimeridian = FALSE, path = NULL)
bathy_r <- as.raster(bathy)
bathy_r <- as.data.frame(bathy_t, xy = TRUE)
b <- ggplot()
geom_raster(bathy_t, mapping = aes(x = x, y = y, fill = layer))
scale_color_gradientn(
colours = c("midnightblue", "skyblue1", "grey", "black"),
breaks = c(-5497,-2000, -0.1, 0.2, 1413))
b
The resulting plot works but only using the midnightblue and skyblue1 color scheme, no grey or black shows up.
CodePudding user response:
Since you're using marmap to download bathymetric data, you might as well use marmap to plot these data. If you want to use ggplot2, it's possible using a few handy marmap functions:
library(marmap)
library(ggplot2)
bathy <- getNOAA.bathy(-80, -70, 40, 32, resolution = 1,
keep = FALSE, antimeridian = FALSE, path = NULL)
#> Querying NOAA database ...
#> This may take seconds to minutes, depending on grid size
#> Building bathy matrix ...
autoplot(bathy, geom = c("raster", "contour"))
scale_fill_etopo()

As explained by chemdork123, you can choose any palette you want using scale_fill_...() functions instead of scale_color_...() functions. A few examples are provided in the ?marmap_autoplot().
When using scale_fill_gradientn(), you should not use breaks to adjust the colors to specific values of depth/altitude, but values instead. ANd since values expects a numeric vector of values between 0 and 1, you can use scales::rescale(). Here is an example with the colors you specified:
autoplot(bathy, geom = c("raster", "contour"))
scale_fill_gradientn(colours = c("midnightblue", "skyblue1",
"grey", "black"),
values = scales::rescale(c(min(bathy), -0.1,
0, max(bathy))))

