Reputation: 516
I am having problems to group colors and present them in legend. The function takes in one level that is not within the data (3rd), and shows it in the legend, but does not do the same with 4th.
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")
The weird thing is that this sometimes works and result should be something like this:
Error code:
Error in `[[<-.data.frame`(`*tmp*`, v, value = c("#FFFF00", "#FFAA00", :
replacement has 4 rows, data has 3
Upvotes: 0
Views: 70
Reputation: 4282
The problem happens because color_var_sens
is not a factor and the guide_legend
tries do replace values that do not exist in color_car_sens
. You should make it a factor. In that way you do not need theguide_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)
Upvotes: 1