1

I'm having some difficulties with color mapping in ggplot2. Two out of the four plots have the same six county variables. However, the "Carbon Monoxide" and "Coarse Particulate matter" subplots only have five (Pierce County is missing).

Each pollutant has a different unit on the y-axis, and labeling individual facets in a single ggplot is a challenge. To get around this, I am generating each plot individually then grouping them together using gridExtra.

Is it possible to apply the same color mapping from the three plots with sixe counties to the carbon monoxide plot?

Here's an example of how I'm making an individual plot:

library(ggplot2)
library(dplyr)
library(gridExtra)


p1 <- ggplot(filter(df, pollutant == "Nitrogen dioxide"), aes(x = as.factor(season), y = value, fill = as.factor(county))) + 
    geom_boxplot(position = "dodge")

    ## I'm excluding a bunch of code to format the font and size of the title/legend/axis labels


g <- grid.extra(p1, p2, p3, p4)

enter image description here

philiporlando
  • 941
  • 4
  • 19
  • 31
  • 2
    Use `scale_color_manual` to assign the same color to each county, regardless of whether a particular county is present in a particular plot. [Here's an example](https://stackoverflow.com/a/46518762/496488). – eipi10 Nov 30 '17 at 00:59
  • Is there a way to assign ggplot2's default color palette when using `scale_color_manual` for the 6 factor levels? – philiporlando Nov 30 '17 at 01:24
  • 1
    `library(scales)` then `hue_pal()(6)` should give the first 6 colors of the default `ggplot2` palette. – neilfws Nov 30 '17 at 02:22
  • This is perfect thanks! I've always wanted to know how to do this... – philiporlando Nov 30 '17 at 02:37

1 Answers1

2

Thanks to some help from the comments, I've managed to produce the desired result. It was surprisingly easier than I thought. The hue_pal() function will definitely be of use to me in the future. Thanks guys!

library(scales)

## determine what the default color palette is for ggplot2 with 6 factor levels:
hue_pal()(6)
#[1] "#F8766D" "#B79F00" "#00BA38" "#00BFC4" "#619CFF" "#F564E3"

## next we need to create a custom color palette using these six colors:
cols <- c("Ada" = "#F8766D", "Bernalillo" = "#B79F00",
          "Multnomah" = "#00BA38", "Pierce" = "#00BFC4",
          "Sacramento" = "#619CFF", "Salt Lake" = "#F564E3")

## I'm mapping each color to the specific factor level (County Name)
## This ensures that each county maintains the same color throughout each plot
## regardless if there are 5 or 6 factor levels!

p1 <- ggplot(filter(df, pollutant == "Nitrogen dioxide"),
             aes(x = as.factor(season),
                 y = value,
                 fill = as.factor(county))) + 
      geom_boxplot(position = "dodge") + 

      ## here's where we'll add our custom color palette:
      scale_fill_manual(values = cols)

p1

enter image description here

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104
philiporlando
  • 941
  • 4
  • 19
  • 31