ggplot plots the thing that comes first in the legend first, and then plots over the top of it the thing that comes second in the legend, ... I would like to reverse that, so it plots whatever comes last in the legend first, followed by whatever comes second-to-last in the legend etc. This is because my lines are overlapping and obscuring each other, and I want the least obscured lines to appear first in the legend. The only thing I can see relevant to this problem is reordering the levels of the grouping factor; however, that changes both the legend order and the plotting order, so gets me nowhere. An example:
library(tidyverse)
df <- tibble(x = seq(from = 0, to = 3.14, by = 0.01),
y1 = sin(x), y2 = sin(10 * x)) %>% pivot_longer(-x)
# Here y1 comes first in the legend, but its line gets obscured by y2:
ggplot(df) + geom_line(aes(x, value, col = name), size = 2)
# change factor order:
df$name <- factor(df$name, levels = c("y2", "y1"))
# Now the y1 line is not obscured by y2, but it's second in the legend:
ggplot(df) + geom_line(aes(x, value, col = name), size = 2)
Can the legend order and plotting order be separated?
y2
undery1
right ? – Ducky1
on top for both. – ChrisW