Consistent color scale and legend between plots when not all levels of a grouping variable are present in the data
Set the factor levels of Colours
to include all possible values, whether present or not in the data at hand, then add drop=FALSE
to scale_colour_manual
:
all.data=data.frame(Date=dates15, Data=ex.data, Colours=colours)
g.cols=c("black", "blue", "pink", "purple")
all.data$Colours = factor(all.data$Colours, levels=sort(c(unique(colours), "Pink Points")))
ggplot(all.data, aes(Date, Data, colour=Colours, group=1)) +
geom_line() +
scale_color_manual(values=g.cols, drop=FALSE) +
xlim(as.POSIXct("2015-01-01 00:00:00"), as.POSIXct("2015-02-12 23:45:00"))