Define some data:
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(ggplot2)
df = tibble(
x=c(0, 0, 1, 1),
y=c(0, 0.1, 1, 1.1),
group=c("a", "b", "a", "b"),
ymin=c(-0.5, -1, 0.5, 0),
ymax=c(0.5, 1, 1.5, 2)
)
If we “just” plot it:
ggplot(df, aes(x, y, ymin=ymin, ymax=ymax, fill=group)) +
geom_ribbon()
Reordering the data frame doesn’t change the plotting order:
df[rev(1:nrow(df)),] %>%
ggplot(aes(x, y, ymin=ymin, ymax=ymax, fill=group)) +
geom_ribbon()
But changing the factor order of the grouping variable does:
df %>%
mutate(group=factor(group, c("b", "a"))) %>%
ggplot(aes(x, y, ymin=ymin, ymax=ymax, fill=group)) +
geom_ribbon()