【发布时间】:2016-04-14 02:53:36
【问题描述】:
下面是一些简单示例数据框和绘图的代码。我想知道如何有条件地为条形着色。我熟悉 scale_fill_manual 来手动给条形上色,但是如果我希望 2016 构面中的 "Satisfied" 比 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)
【问题讨论】: