Drop = FALSE with scale_fill_identity

Does anyone know if this is expected to work?

library(ggplot2)

df <- data.frame(
  x = 1:4,
  y = 1:4,
  colour = c("red", "green", "blue", "yellow")
)

ggplot(df, aes(x, y)) +
geom_tile(aes(fill = colour)) +
scale_fill_identity(
 "trt", 
 labels = letters[1:2], 
 breaks = c("white", "black"), 
 guide = "legend", 
 drop = FALSE
)

ggplot2 version: ggplot2_2.2.1

"Work" in this case would be a plot with a legend that has the specified labels with the symbols having the colors white and black. According to the documentation for scale_fill_identity and discrete_scale I would have expected the results to be similar to specifying drop = FALSE in scale_fill_manual (for example: https://stackoverflow.com/questions/37698773/ggplot2-legend-does-not-show-all-categories-even-with-drop-false/37700258).

I know it doesn't make a lot of sense to do so with the example but I have a use case where it does... Thanks in advance for any insight!

Hi @jasonserviss , if you convert the colour variable to a factor when you construct the data frame with levels for black and white in addition to the observed values of colour I think the result is what you are after.
For your actual use case you may need to convert the variable to a factor and then use the forcats package to get the factor levels how you want them. Hope this helps

library(ggplot2)

df <- data.frame(
  x = 1:4,
  y = 1:4,
  colour = factor(
    c("red", "green", "blue", "yellow"),
    levels = c("red", "green", "blue", "yellow","black","white")
  )
)

ggplot(df, aes(x, y)) +
  geom_tile(aes(fill = colour)) +
  scale_fill_identity(
    "trt", 
    labels = letters[1:2], 
    breaks = c("black", "white"), 
    guide = "legend", 
    drop = FALSE
  )

it looks like this:
Rplot01

2 Likes

@adamgruer In my actual use case I run into a problem with duplicated factor levels but I think I might be able to work around that (potentially with your suggestion regarding forcats). Thanks a lot for the help!!