1
votes

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?

1
So you want y2 under y1 right ?Duck
I'm trying to get whichever line is on top in the plot to also be on top in the legend. For example y1 on top for both.ChrisW

1 Answers

0
votes

Thanks to Michelle Kendall for the answer: specifying the breaks when specifying the colours, thus

df <- tibble(x = seq(from = 0, to = 3.14, by = 0.01),
             y1 = sin(x), y2 = sin(10 * x)) %>% pivot_longer(-x)
# Specify the order for plotting lines:
df$name <- factor(df$name, levels = c("y2", "y1"))
ggplot(df) +
  geom_line(aes(x, value, col = name), size = 2) +
  # specify the order for the legend:
  scale_color_manual(values=c("blue", "red"), breaks=c("y1", "y2"))

enter image description here