0

Normally, the order of items in a legend can be controlled by using a factor and ensuring the levels are in the desired order. For example, in the code below this works exactly as expected, except in the last plot, where the legend orders itself incorrectly (i.e., it switches from the desired order of -1.1, -0.9, 0 to the alphabetical, but not desired order of -0.9, -1.1, 0). What are some approaches to get around this issue? Also, is it a bug?

library(dplyr)
library(ggplot2)

Z <- tibble(x = c(-1.11, -0.9,  0), x_fct = factor(x)) # Note: factor levels are in correct (i.e., numerical) order

Z |> # Legend in correct order (but no 'circle filled' yet)
  ggplot(aes(x, x, color = x_fct)) +
  geom_point() 

Z |> # Legend is in correct order but `geom_poin()` is obscured by 'circle filled'
  ggplot(aes(x, x, color = x_fct)) +
  geom_point() +
  geom_point(shape = 'circle filled', size = 10, fill='grey', data = ~ . |> filter(x > min(x)))

Z |> # Legend in correct order
  ggplot(aes(x, x, color = x_fct)) +
  geom_point(shape = 'circle filled', size = 10, fill='grey', data = ~ . |> filter(TRUE)) + # `data=...` just to mirror above
  geom_point() 

Z |> # Legend in INCORRECT order
  ggplot(aes(x, x, color = x_fct)) +
  geom_point(shape = 'circle filled', size = 10, fill='grey', data = ~ . |> filter(x > min(x))) +
  geom_point() 
banbh
  • 1,331
  • 1
  • 13
  • 31

1 Answers1

0

I just noticed the following answer: https://stackoverflow.com/a/52560667/239838

Based on that a working solution is:

Z |> # Legend in correct order
  ggplot(aes(x, x, color = x_fct)) +
  geom_point(shape = 'circle filled', size = 10, fill='grey', data = ~ . |> filter(x > min(x))) +
  geom_point() +
  scale_color_discrete(drop = FALSE)

I suspect this is the expected way to deal with this.

banbh
  • 1,331
  • 1
  • 13
  • 31