下面是一个简单示例数据框和图表的代码。我想知道如何有条件地着色柱状图。我熟悉使用
scale_fill_manual
手动给柱子上色,但如果我想让"Satisfied"
在2016
方面如果低于2015
中的"Satisfied"
,那该怎么办呢?也许是一个红色的警告边框或不同的颜色,比如橙色(只是举个例子)。这不是最好的例子,但如果我有一个年度最高分数的图表,当它们下降到一定百分比以下时,这将非常有用。我尝试了一些"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)