I'm making a map and want to add rectangles with a horizontal color gradient (darkest color on the left, fading to white on the right). I initially made the rectangles with geom_rect the most similar examples I could find in other SO posts was using geom_tile with a variable fill. I tried that below by generating a dummy column newcol that just holds the difference between the xmax and xmin of the real data so that the fill gradient would vary from left to right in each rectangle, but as you can see below, the rectangles still don't have a gradient. Any ideas?
library(ggplot2)
library(sf)
library(rnaturalearth)
library(tidyverse)
states <- ne_states(country = c("United States of America","Canada"), returnclass = "sf")
rectangles <- data_frame(
y = (35:44)+0.5,
xmin = c(-75.5, -75.770333, -75.683333, -75.916667, -74.613, -74.0315,
-71.916667, -70.666667, -70.466667, -68.4),
xmax = c(-74.8, -74.616667, -73.983333, -72.8, -69.216667, -66.416667,
-65.65, -65.675833, -66.516667, -66.721667)
)%>%
pivot_longer(cols = c(xmax, xmin), names_to="identity", values_to="x") %>%
group_by(y) %>%
mutate(meanx = mean(x),
newcol = x - min(x))
ggplot(data = states) +
geom_sf() +
geom_tile(data = rectangles, aes(x=meanx, y=y, width=2, height=1, fill=newcol), color="black") +
scale_fill_gradient(low="darkblue", high="white") +
coord_sf(xlim = c(-80, -65), ylim = c(34, 45.5), expand = FALSE) +
NULL
