2017-07-07 88 views
1

我有問題來分組顏色並將其呈現在圖例中。該函數採用不在數據內的一個級別(第3個),並將其顯示在圖例中,但與第4個不同。修改geom_bar的顏色

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 

回答

2

的問題發生,因爲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)