Skip to content

partially named values in scales #1497

Closed

Description

@rpruim

If I understand current behavior correctly, the values vector in a scale function is matched by name if there are (any) names and by position otherwise. Would you consider matching by names when the name is present and by position among unnamed items when the name isn't there?

I'm imagining a use case like this:

scale_colour_discrete <- 
  function(values = c(male = "skyblue", female = "pink", "navy", "red", "green", "purple"), ...) {
    scale_color_manual(values = values, ...)
  }

The idea is that this would use blue and pink for male and female, but use navy, red, green, purple for other levels. In the context of a given document, one could expand this to fix colors for levels that will occur in many contexts but still make it possible to plot other data without having to keep changing/specifying the scale function.

Of course, this idea should work for other things (like fill, size, alpha, etc.) as well.

PS. Redefining scale_colour_discrete() like this should really be documented somewhere.

Activity

  1. hadley commented on Jan 25, 2016

    @hadley
    Member

    I like the idea, but I'm unlikely to have the time to implement it. But if you could figure out how to implement the matching bit, I can slot it into the right place:

    The important code is DiscreteScale$map():

      map = function(self, x, limits = self$get_limits()) {
        n <- sum(!is.na(limits))
        pal <- self$palette(n)
    
        if (is.null(names(pal))) {
          pal_match <- pal[match(as.character(x), limits)]
        } else {
          pal_match <- pal[match(as.character(x), names(pal))]
          pal_match <- unname(pal_match)
        }
    
        ifelse(is.na(x) | is.na(pal_match), self$na.value, pal_match)
      }

    So you'd need to replace the if statement with more sophisticated logic.

  2. added
    feature
    on Jan 25, 2016
  3. locked as resolved and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions