I am creating a scatter plot in R where users can add or remove a horizontal line which shows a fixed reference value. In doing so, I noticed that changing the name of the reference line re-orders the legend, so that sometimes the horizontal line appears before the scatter legend elements, and sometimes afterwards.
Compare:
to
Below is a reproduceable example
YEAR = as.integer(rep(2010:2020,5))
SERIES_NAME = rep(LETTERS[1:5], each = 11)
OBS_VALUE = runif(n = 55, min = -5, max = 20)
EA = ifelse(SERIES_NAME=='A', 'Option 1', 'Option 2')
df <- data.frame(YEAR=YEAR,
SERIES_NAME=SERIES_NAME,
OBS_VALUE=OBS_VALUE,
EA=EA)
Comment out one or the other of the two lines to produce a graph where to name the horizontal line on the legend.
aaaaaaa <- "RGCUZYMSFP" # appears above
aaaaaaa <- "IZTCYUXGBO" # appears below
The graphs are then produced:
df %>%
select(YEAR,SERIES_NAME, OBS_VALUE, EA) %>%
ggplot() +
ggplot2::geom_point(
ggplot2::aes(
x = YEAR,
y = OBS_VALUE,
col = EA),
size = 2) +
ggplot2::guides(
color = ggplot2::guide_legend(nrow = 2,
byrow = TRUE))+
scale_linetype_manual(values = 2) +
scale_x_continuous(breaks = seq(2010,2020,5))+
geom_hline(aes(yintercept = EAMean,
linetype = aaaaaaa),
size = 1, color = "black")
I've also noticed that changing the name of the variable changes the output. If I change the name of the variable from aaaaaaaa (8 times the letter a) to aaaaaaa (7 times the letter a) and update the code for the horizontal line accordingly, the legend re-orders
Is there a way that I can be more consistent in controlling where my legend item goes?


