Ggplot2 中的有条件着色条

Mik*_*ike 3 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)
Run Code Online (Sandbox Code Playgroud)

bee*_*oot 6

向数据框中添加新变量可能是最简单的:

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

然后你可以这样做:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果您想根据条件更改填充,您可以执行以下操作:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述