I am trying to segment ggplot geom_ribbon fill based on a column (“type”). But type in my dataset alternates, and I can’t figure out how to get ggplot to not make a continuous ribbon between the types.
I want to end up with something like this:
But I keep getting this:
For whatever reason, it seems to work fine and dandy if the type does not alternate. I’m really hoping there is a solution out there that doesn’t involve carving my large dataset into tiny dfs
I’ve tried every version of group and scale_fill that I can imagine. I’ve also tried putting the colors as a column in the df, but to no avail. Help!
df = data.frame(
type = c("a","a","b","b","a","a","b","b"),
xdat = seq(1, 8),
ydat = c(5,6,8,9,6,7,9,10)
)
type_colors = c("yellow", "blue")
ggplot(df, aes(x = xdat, y = ydat, ymin = ydat - 1, ymax = ydat + 1, fill = type) ) +
geom_ribbon(aes(fill = factor(type))) +
scale_fill_manual(values = type_colors, guide = "none") +
geom_line()