In ggplot2/facet_wrap, in given facet ,how to change specific columns fill color

48 Views Asked by At

In ggplot2/facet_grid, how to change column a and b fill in red in facet gap ?

enter image description here

library(tidyverse)
data <- data.frame(category=c('a','b','c','d'),actual=c(10,7,6,3),budget =c(11,12,4,1))


data %>% mutate(gap = actual - budget) %>% gather(key='item',value='amount',-category) %>% 
  ggplot(aes(x=category,y=amount,fill=item))+
  geom_col()+
  scale_fill_brewer(palette = "Spectral",direction=1)+
  facet_wrap(~ item,ncol=1)

I try to replace geom_col() to geom_col(aes(fill = if_else(amount<0 & item=='gap','red','lightblue'))) , it's failed

data %>% mutate(gap = actual - budget) %>% gather(key='item',value='amount',-category) %>% 
      ggplot(aes(x=category,y=amount,fill=item))+
      geom_col(aes(fill = if_else(amount<0 & item=='gap','red','lightblue')))+
      scale_fill_brewer(palette = "Spectral",direction=1)+
      facet_wrap(~ item,ncol=1)
2

There are 2 best solutions below

2
user123456 On BEST ANSWER

One way would be to use a nested ifelse and scale_fill_manual:

  data %>% 
    mutate(gap = actual - budget) %>% 
    gather(key = 'item', value = 'amount', -category) %>% 
    
        ggplot(aes(x = category, y = amount, fill = item)) +
        geom_col(aes(fill = ifelse(amount < 0 & item == 'gap', 'gap2', 
                                   ifelse(amount > 0 & item == 'gap', 'gap1', item)))) +
        scale_fill_manual(values = c(scales::brewer_pal(palette = "Spectral", direction = 1)(3), 'red')) +
        facet_wrap(~ item, ncol = 1)

enter image description here

0
jared_mamrot On

One potential option is to specify the colours as required, e.g.

library(tidyverse)
data <- data.frame(category=c('a','b','c','d'),actual=c(10,7,6,3),budget =c(11,12,4,1))

data %>% mutate(gap = actual - budget) %>%
  pivot_longer(-category,
               names_to = 'item',
               values_to ='amount') %>% 
  ggplot(aes(x = category,
             y = amount,
             fill = case_when(
               item == "gap" & amount < 0 ~ "red",
               item == "actual" ~ "#EE9164",
               item == "budget" ~ "#FFFCC6",
               item == "gap" & amount > 0 ~ "#A6D39A",
               TRUE ~ NA))) +
  geom_col()+
  scale_fill_identity()+
  facet_wrap(~item, ncol = 1)

Created on 2023-12-22 with reprex v2.0.2