R Ggplot2中的条状着色条
下面是一个简单示例dataframe和plot的一些代码。我想知道如何有条件地给这些条上色。我熟悉用R Ggplot2中的条状着色条,r,ggplot2,R,Ggplot2,下面是一个简单示例dataframe和plot的一些代码。我想知道如何有条件地给这些条上色。我熟悉用scale\u fill\u manual手动给条形图上色,但是如果我想让2016方面的“满意”变成不同的颜色,如果它的百分比低于2015中的“满意”,该怎么办。可能是红色的警告边框或其他颜色,如橙色(仅举一个例子) 这并不是最好的例子,但如果我有一个一年比一年的顶部框分数的图,这将是有用的,让酒吧改变颜色,如果他们下降到一定的百分比以下。我尝试过使用“color=ifelse(Perc
scale\u fill\u manual
手动给条形图上色,但是如果我想让2016
方面的“满意”
变成不同的颜色,如果它的百分比低于2015
中的“满意”
,该怎么办。可能是红色的警告边框或其他颜色,如橙色(仅举一个例子)
这并不是最好的例子,但如果我有一个一年比一年的顶部框分数的图,这将是有用的,让酒吧改变颜色,如果他们下降到一定的百分比以下。我尝试过使用“color=ifelse(Perc<60,“橙色”、“绿色”
组合,但无法使其正常工作。我不确定如何构造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)
Year向数据框中添加新变量可能是最容易的:
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()
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()
df.prop$fill=0.6,“#00BFC4”,“#F8766D”))
ggplot(df.prop,aes(x=服务,y=Perc,fill=填充))+
几何图形栏(stat=“identity”,position=“dodge”)+
几何图形文字(aes(标签=百分比(Perc)),位置=位置减淡(宽度=1),
vjust=1.5,尺寸=3)+
连续缩放(标签=百分比)+
平面网格(~年)+
比例填充标识()
谢谢你的回答,效果很好。只需一个后续问题,答案允许我添加彩色边框,但我如何将实际的条形图颜色改为橙色,而不仅仅是轮廓?如何获得第二张图表的图例?