facet_grid()和颜色条件

时间:2018-01-19 06:47:16

标签: r ggplot2 visualization facet-grid

我对可视化有一些疑问。我有数据帧:

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))    

我需要按条件设置颜色:

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

我尝试了三种不同的版本,而且所有这些版本的工作都不正确。

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)))

然后我使用facet_grid()我的颜色条件无法正常工作。但它不使用facet_grid()就可以正常工作。有什么问题?

1 个答案:

答案 0 :(得分:0)

这样的事,

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