2

This is mere curiosity and a follow up question on ggplot wrong color assignment (and related questions). An alternative to using scale_..._identity is the use of I in aes. However, adding a legend seems then not possible with the specification of guide = "legend" (which I thought should work using guides). I am just curious why this wouldn't work?

library(ggplot2)
library(patchwork)
df <- data.frame(x = 1:2, y = 1, mycols = colors()[c(10,30)])

  ## works
ggplot(df) +
  geom_point(aes(x = x, y = y, colour = mycols)) +
  scale_color_identity(guide = "legend") +
  labs(title = "legend as expected") +
  
ggplot(df) +
  geom_point(aes(x, y, color = I(mycols))) +
## doesn't work - why?
  guides(color = "legend") +
  labs(title = "no legend")

in addition - ... + scale_color_identity() + guides(color = "legend") also doesn't make a legend.

tjebo
  • 21,977
  • 7
  • 58
  • 94
  • It seems you can use `scale_color_identity(guide="legend")` rather than `guides(color = "legend")` to get the legend – MrFlick Aug 11 '22 at 14:43
  • OK. I was just clarifying that `scale_color_identity(guide = "legend")` works both with and without the `I()`. You only used it without in the example. I've not really seen people use `I()` -- is that actually documented somewhere? `scale_color_identity()` on it's own doesn't work because it default to `guide="none"`. It seems unnecessary to also name the color what it is in the legend in most cases. – MrFlick Aug 11 '22 at 14:47
  • 1
    @MrFlick usually the `guides(color = ...)` layer should override `scale_color_...(guide = ...)`, see for example `ggplot(df) + geom_point(aes(x = x, y = y, colour = mycols)) + scale_color_discrete(guide = "none") + guides(color = "legend") ` - thus my question – tjebo Aug 11 '22 at 14:56
  • 1
    Ok. This is interesting. I think it has to do with [this line](https://github.com/tidyverse/ggplot2/blob/d699fb1bbe3dca01bef2d72da4cfc4bbfac047c1/R/scale-identity.r#L149). It seems the scale is not trained if the default guide is none. It looks like `guides()` is not changing that value soon enough. If you explictly call `scale_color_identity` with `guide=` then you skip that default training problem. – MrFlick Aug 11 '22 at 15:27

0 Answers0