Search code examples
rggplot2geom-barfacet-wrap

Change color of bars in one facet panel only


Below is a simple code for ggplot bar graph with facet_wrap:

categories <- c("category 1", "category 2", "category 3")
groups <- c("A", "B", "C", "D")

df <- expand.grid(category = categories, group = groups)
df$value <- rnorm(12, 1, 0.5)

ggplot(df, aes(x = category,
               y = value)) + 
  geom_bar(stat = "identity") + 
  facet_wrap(~ group)

Now I want the bars for the group C to be red (just for the group C). How can I do it?


Solution

  • This is very similar to the other question I linked. However, your comment indicated that the connection was not clear. The key is to realise that you are setting the color by group, but that you can set the color and also create facets by the same column.

    Define your colors:

    colors  <- rep("grey50", length(unique(df$group)))  |>
        setNames(unique(df$group))
    colors["C"]  <- "red"
    
    
    # `colors` is a named vector that looks like this:
    #           A        B        C        D 
    #    "grey50" "grey50"    "red" "grey50" 
    

    Then draw the plot setting the fill aesthetic to group, and use scale_fill_manual() to specify the colors we defined:

    ggplot(df, aes(
        x = category,
        y = value
    )) +
        geom_bar(stat = "identity", aes(fill = group)) +
        scale_fill_manual(values = colors) +
        facet_wrap(~group)
    

    enter image description here