As the question says, I’d like to plot data colored by a factor (discrete) on top of a raster elevation map (a continuous scale). I’ve tried specifying the scales separately (with scale_fill_gradientn() and scale_color_manual()), but still the error persists.
Is there a way to do this, or do I just have to drop the elevation raster?
Here’s a reproducible example:
library(spData)
library(elevatr)
library(dplyr)
california <- us_states %>%
filter(NAME == "California")
# Import elevation data
ca.elevations <- get_elev_raster(locations = california, z = 5, clip = "locations")
# Convert elevation raster to df, keeping only elevation, not bathymetry
ca.elevation.df <- raster::as.data.frame(ca.elevations, xy = TRUE) %>%
rename(elevation = 3) %>%
na.omit() %>%
filter(elevation >= 0)
background.map <- ggplot()+
geom_tile(data = ca.elevation.df, aes(x = x, y = y, fill = elevation))+
scale_fill_gradientn(colours= c("gray90", "black"), values= scales::rescale(c(0, 300, 900, 1000, 1900, 2000, 3900, 4000, 10000)), guide = "none")+
geom_sf(data = california, fill = NA)
# Add discrete data to map
pie.data <- data.frame(pie = c("a","b", "c"), part.1 = rep(0.5, 3), part.2 = rep(0.5, 3),
lat = c(34,36,38), long = c(122,120,118))
# Works
ggplot()+
geom_scatterpie(data = pie.data,
aes(x = long, y = lat, group = pie),
cols = c("part.1", "part.2"))
# Doesn't work
background.map+
geom_scatterpie(data = pie.data,
aes(x = long, y = lat, group = pie),
cols = c("part.1", "part.2"))
>Solution :
One way to manage this is adding a new scale with ggnewscale. Please note I modified your data, making all the longitudes negative in the pie.data data frame.
library(spData)
library(elevatr)
library(dplyr)
library(scatterpie)
california <- us_states %>%
filter(NAME == "California")
# Import elevation data
ca.elevations <- get_elev_raster(locations = california, z = 5, clip = "locations")
#> Mosaicing & Projecting
#> Clipping DEM to locations
#> Note: Elevation units are in meters.
# Convert elevation raster to df, keeping only elevation, not bathymetry
ca.elevation.df <- raster::as.data.frame(ca.elevations, xy = TRUE) %>%
rename(elevation = 3) %>%
na.omit() %>%
filter(elevation >= 0)
background.map <- ggplot()+
geom_tile(data = ca.elevation.df, aes(x = x, y = y, fill = elevation))+
scale_fill_gradientn(colours= c("gray90", "black"), values= scales::rescale(c(0, 300, 900, 1000, 1900, 2000, 3900, 4000, 10000)), guide = "none")+
geom_sf(data = california, fill = NA)
# Add discrete data to map
pie.data <- data.frame(pie = c("a","b", "c"), part.1 = rep(0.5, 3), part.2 = rep(0.5, 3),
lat = c(34,36,38), long = c(-122,-120,-118))
# Works now
background.map+
ggnewscale::new_scale_fill() +
geom_scatterpie(data = pie.data,
aes(x = long, y = lat, group = pie),
cols = c("part.1", "part.2"))

Created on 2023-04-07 with reprex v2.0.2