Search code examples
rggplot2fillbinning

How to use specific filling colors when using scale_fill_binned()?


I would like to use my own filling colors (ex: c("red", "blue", "grey50", "black")) when using function scale_fill_binned() withing a ggplot code. How can I do this?

Here is a minimal reproducible example:

library(tidyverse)

dat <- mtcars %>% 
       group_by(cyl) %>% 
       summarise(n = n(),
                 mean_hp = mean(hp)) %>% 
       ungroup

ggplot(data = dat, aes(x = cyl, y = mean_hp, size = n, fill = n)) +
  geom_point(shape = 21) +
  scale_size_binned(breaks = c(8, 10, 12), guide = guide_bins(show.limits = T)) +
  scale_fill_binned(breaks = c(8, 10, 12), guide = guide_bins(show.limits = T), type = "viridis") +
  labs(x = "Cylinder", y = "Mean hp", fill = "Nb of cars", size = "Nb of cars") +
  theme_minimal()

Here is what the output looks like:

enter image description here


Solution

  • With the comment of @teunbrand, I was able to come up with something.

    cols <- c("red", "blue", "grey50", "black")
    ggplot(data = dat, aes(x = cyl, y = mean_hp, size = n, fill = n)) +
      geom_point(shape = 21) +
      scale_size_binned(breaks = c(8, 10, 12), guide = guide_bins(show.limits = T)) +
      labs(x = "Cylinder", y = "Mean hp", fill = "Nb of cars", size = "Nb of cars") +
      theme_minimal() +
      binned_scale(aesthetics = "fill", scale_name = "custom", 
                   palette = ggplot2:::binned_pal(scales::manual_pal(values = cols)),
                   guide = "bins",
                   breaks = c(8, 10, 12), limits = c(min(dat$n), max(dat$n)), show.limits = T)
    

    Here is what the output looks like:

    enter image description here