修改geom_bar的颜色

时间:2017-07-07 21:39:31

标签: r ggplot2

我遇到了将颜色分组并将其呈现在图例中的问题。该函数采用不在数据(第3个)内的一个级别,并在图例中显示,但不会对第4个级别执行相同操作。

x <- structure(list(date = structure(c(1498521600, 1498525200, 1498528800, 
1498532400, 1498536000, 1498539600, 1498543200, 1498546800, 1498550400, 
1498554000, 1498557600, 1498561200, 1498564800, 1498568400, 1498572000, 
1498575600, 1498579200, 1498582800), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), irish_rules_sensitive = c(0, 0, 0, 0, 0, 1, 
2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("date", "irish_rules_sensitive"
), row.names = c(NA, -18L), class = c("tbl_df", "tbl", "data.frame"
))
color_var_sens <- vector(mode = "double",length = length(x$irish_rules_sensitive))
color_var_sens[color_var_sens== '0']<- NA
color_var_sens[x$irish_rules_sensitive>=1 & x$irish_rules_sensitive<=3] <- "#FFFF00" 
color_var_sens[x$irish_rules_sensitive>=3 & x$irish_rules_sensitive<6] <- "#FFAA00" 
color_var_sens[x$irish_rules_sensitive>=6 & x$irish_rules_sensitive<9] <- "#FF5500"
color_var_sens[x$irish_rules_sensitive>=12] <- "#FF0000" 


p5 <- ggplot(x)+ 
  geom_col(aes(x = date, y = irish_rules_sensitive, color = color_var_sens, group = 1), size= 1)+
  scale_y_continuous(limits = c(0, 40) )+
  labs(x="", y="Accum. EBHours")+
  scale_color_identity("Modified Irish Rules", breaks= rev(levels(as.factor(color_var_sens)))[c(1,2,3,4)], 
                       labels = c("Low ","Medium", "High", "Very High"),
                       guide = "legend",drop = FALSE)
p5 + guides(colour=guide_legend(override.aes=list(fill=c("#FFFF00","#FFAA00","#FF5500", "#FF0000" ))), size = "none")

奇怪的是,这有时会起作用,结果应该是这样的:

错误代码:

    Error in `[[<-.data.frame`(`*tmp*`, v, value = c("#FFFF00", "#FFAA00",  : 
  replacement has 4 rows, data has 3

1 个答案:

答案 0 :(得分:1)

问题出现是因为color_var_sens不是因素而guide_legend次尝试会替换color_car_sens中不存在的值。你应该把它作为一个因素。这样您就不需要guide_legend

color_var_sens <- factor(level=rev(c("#FFFF00","#FFAA00","#FF5500", "#FF0000" )), ordered=T)
color_var_sens[color_var_sens== '0']<- NA
color_var_sens[x$irish_rules_sensitive>=1 & x$irish_rules_sensitive<=3] <- "#FFFF00" 
color_var_sens[x$irish_rules_sensitive>=3 & x$irish_rules_sensitive<6] <- "#FFAA00" 
color_var_sens[x$irish_rules_sensitive>=6 & x$irish_rules_sensitive<9] <- "#FF5500"
color_var_sens[x$irish_rules_sensitive>=12] <- "#FF0000" 


ggplot(x,aes(x = date, y = irish_rules_sensitive, fill = color_var_sens))+ 
  geom_col( size= 1)+
  scale_y_continuous(limits = c(0, 40) ) +
  labs(x="", y="Accum. EBHours") +
  scale_fill_identity("Modified Irish Rules", breaks= rev(levels(as.factor(color_var_sens))), 
                       labels = c("Low ","Medium", "High", "Very High"),
                       guide = "legend",drop = FALSE)