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.