Skip to content

scale_color_distiller with divergent palette does not produce mid-color correct #3072

Closed
@yosukefk

Description

@yosukefk

When scale color distiller is used with divergent color palette, color for mid point does not have the mid point specified by http://colorbrewer2.org. For example, RdBu uses #f7f7f7 for mid color when number of divisions are odd. But with distiller, I am getting #e9e0db which has slight pink shade. I believe it should give neutral color for the mid point. Fix is very easy, change the argument for brewer_pal generated function from 6 to 7. https://github.com/tidyverse/ggplot2/blob/master/R/scale-brewer.r#L87

library(ggplot2)
library(scales)

v <- -1:1
dat <- data.frame(x = v, y = rep(0,3))

# normal way to make plot
p <- ggplot(dat) + geom_point(aes(x=x,y=y,color=v), size=12) +
 scale_color_distiller(palette='RdBu',direction=1, limits=c(-1,1))
# this gives mid point (0) with pink shade
p

# took code from here, 
# https://github.com/tidyverse/ggplot2/blob/master/R/scale-brewer.r#L87-L88
# changed to 7 color per palette, instead of 6
library(scales)
my.scale_colour_distiller <- function(..., type = "seq", palette = 1, direction = -1, values = NULL, space = "Lab", na.value = "grey50", guide = "colourbar", aesthetics = "colour") {
  # warn about using a qualitative brewer palette to generate the gradient
  type <- match.arg(type, c("seq", "div", "qual"))
  if (type == "qual") {
    warning("Using a discrete colour palette in a continuous scale.\n  Consider using type = \"seq\" or type = \"div\" instead", call. = FALSE)
  }
  continuous_scale(aesthetics, "distiller",
    gradient_n_pal(brewer_pal(type, palette, direction)(7), values, space), na.value = na.value, guide = guide, ...)
  # NB: 6 colours per palette gives nice gradients; more results in more saturated colours which do not look as good
}

# try again with new function
p <- ggplot(dat) + geom_point(aes(x=x,y=y,color=v), size=12) +
 my.scale_colour_distiller(palette='RdBu',direction=1, limits=c(-1,1))
# gives correct color
p

Created on 2019-01-18 by the reprex package (v0.2.1)


Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviortidy-dev-day 🤓Tidyverse Developer Day

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions