Skip to content

values vector in scale_color_manual #4534

Closed
@numpde

Description

@numpde

The behavior of scale_color_manual(values = ...) seems to have changed recently and broke many of my plots.

Consider this example:

suppressPackageStartupMessages({
  library(ggplot2)
  library(dplyr)
})

color_map <- list(r = "red", g = "green", b = "blue")

randu %>%
  mutate(color_key = as.factor(if_else(x > y, "r", "g"))) %>%
  ggplot(aes(x = x, y = y, fill = color_key)) + 
  scale_fill_manual(values = color_map) +
  geom_point(shape = 21, size = 7)

It now produces a figure with the blue color also in the legend.
I find that the following works (blue does not appear in the legend):

randu %>%
  mutate(color_key = as.factor(if_else(x > y, "r", "g"))) %>%
  {
    ggplot(., aes(x = x, y = y, fill = color_key)) + 
      scale_fill_manual(values = color_map, breaks = .$col) +
      # scale_fill_manual(values = color_map[.$col]) +  # Alternative
      geom_point(shape = 21, size = 7)
  }

But this code looks unhappy. Is there a more robust way, in particular without extra temporary variables?

Is there somethin like breaks = .df$fill? This would be useful in many contexts.

Sidenote. This would make more sense to me:

scale_fill_manual(values = color_map)  # no blue in the legend
scale_fill_manual(values = color_map, breaks = names(color_map))  # with blue in the legend

==

For lols, this works, too:

gglast <- function(what) {
  p <- ggplot2::last_plot()
  q <- p$mapping[[deparse(substitute(what))]]
  rlang::eval_tidy(q, data = p$data)
}

randu %>%
  mutate(color_key = as.factor(if_else(x > y, "r", "g"))) %>%
  ggplot(aes(x = x, y = y, fill = color_key)) + 
  scale_fill_manual(values = color_map, breaks = gglast(fill)) +
  geom_point(shape = 21, size = 7)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions