Ggplot2中的条件着色条

时间:2016-04-14 02:53:37

标签: r ggplot2

下面是一些简单示例数据框和图的代码。我想知道如何有条理地为酒吧着色。我熟悉scale_fill_manual手动为条形设置颜色,但如果我"Satisfied"方面的2016颜色不同,如果它的百分比低于"Satisfied"中的2015。也许是红色警告边框或不同颜色,如橙色(仅举例)。

这不是最好的例子,但是如果我有一个年度顶盒评分的情节,如果它们下降到一定百分比以下就会改变颜色会很有用。我尝试使用"colour = ifelse(Perc < 60, "orange", "green"组合,但无法使其发挥作用。我不确定如何构造ifelse语句或将其放在ggplot代码中的位置。

Year<-c(2015, 2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016, 2016)

Service<-c("Satisfied", "Satisfied", "Satisfied", "Dissatisfied", "Dissatisfied",
           "Satisfied", "Satisfied", "Dissatisfied", "Dissatisfied", "Dissatisfied")

df <- data.frame(Year, Service)

library(dplyr)
df.prop <- df %>%
            count(Year, Service) %>%
            mutate(Perc = prop.table(n))

library(ggplot2)
ggplot(df.prop, aes(x = Service, y = Perc, fill = Service)) +
       geom_bar(stat = "identity", position = "dodge") +
       geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1),
                 vjust = 1.5, size = 3) +
       scale_y_continuous(labels = percent) +
       facet_grid( ~ Year)

1 个答案:

答案 0 :(得分:2)

最容易向数据框添加新变量:

df.prop$colour <- ifelse(df.prop$Service == "Satisfied" & df.prop$Perc < 0.6, "orange", NA)

然后你可以这样做:

ggplot(df.prop, aes(x = Service, y = Perc, fill = Service, colour=colour)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1),
            vjust = 1.5, size = 3, colour="black") +
  scale_y_continuous(labels = percent) +
  facet_grid( ~ Year) +
  scale_colour_identity()

enter image description here

如果您想根据您可以做的条件更改填充:

df.prop$fill <- ifelse(df.prop$Service == "Satisfied" & df.prop$Perc < 0.6, "orange", ifelse(df.prop$Service == "Satisfied" & df.prop$Perc >= 0.6, "#00BFC4", "#F8766D"))

ggplot(df.prop, aes(x = Service, y = Perc, fill = fill)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1),
            vjust = 1.5, size = 3) +
  scale_y_continuous(labels = percent) +
  facet_grid( ~ Year) +
  scale_fill_identity()

enter image description here