facet_grid() and color condition

by amyard   Last Updated January 19, 2018 17:26 PM

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?



Answers 1


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

Eric Fail
Eric Fail
January 19, 2018 14:26 PM

Related Questions


Using ggplot2 to draw bar plot

Updated April 30, 2017 00:26 AM



Facet_grid two segments y axis

Updated August 07, 2017 14:26 PM