Search code examples
rggplot2visualizationfacet-grid

facet_grid() and color condition


I have some questions about visualization. I have dataframe:

df <- data.frame(
  Campaign = c('month 10', 'month 11','month 10', 'month 11','month 10', 'month 11'),
  name = c('TI', 'TI', 'SI', 'SI', 'NPS', 'NPS'),
  values = c(93,96,83,84, 43,36))    

I need to set colors by condition:

ifelse(df$values>95,'green',ifelse(df$values>90,'yellow','red'))

I had try three different version , and all of them don’t work correct.

1.
p <- ggplot(df, aes(name,values, group = Campaign))+
geom_bar(stat = 'identity',aes(fill = factor(name)))+
facet_grid(.~Campaign)
p + scale_fill_manual(values = paste(ifelse(df$values>
      95,'green',ifelse(df$values>90, 'yellow',' red'))))+

2. cols <-ifelse(df$values>95,'green',ifelse(df$values>90,'yellow','red'))
p + scale_fill_manual(values = cols)

3. df$color <- ifelse(df$values>95,'green',ifelse(df$values>90,'yellow','red'))
p + scale_fill_manual(values = paste(df$color))
and this:
p + scale_fill_manual(values = unique(as.character(df$color)))

Then I use facet_grid() my color condition doesn’t work correctly. But it works well without using facet_grid(). What is wrong?


Solution

  • something like this,

    df$fill.group = cut(df$values, breaks=c(-Inf, 90, 95, Inf))             
    
    # install.packages(c("tidyverse"), dependencies = TRUE)
    library(ggplot2)
    
    ggplot(df, aes(name,values, fill=fill.group)) + 
           geom_bar(stat = 'identity') + facet_grid(.~Campaign) +
           scale_fill_manual(values=c("red", "yellow", "green")
          )
    

    dd