I'm trying to solve the following problem: how to join lines of different aesthetics/groups in ggplot and maintain the color of a certain group. It is best to see the examples below for a better understanding of what I mean.
Consider the following code:
set.seed(870123)
library(ggplot2)
example_data <- data.frame(Date = seq.Date(as.Date("2020-01-01"),length.out = 20,by = "month"),
Series = rnorm(20) 1,
Grouping = c(rep(c("Group1"),10),rep(c("Group2"),10)))
print(ggplot(example_data,aes(x = Date, y = Series))
geom_line(aes(color = Grouping))
geom_point(aes(color = Grouping))
scale_color_manual(values = c(Group1 = "blue", Group2 = "red")))
Which generates the plot:
My problem is that ggplot won't join the lines where the grouping variable changes. I would like, for example, there to be a red line joining the last blue point to the first red point. One way to solve such issue would be to not specify any color aesthetic for the geom_line portion, as below, but this is NOT what I want:
print(ggplot(example_data,aes(x = Date, y = Series))
geom_line()
geom_point(aes(color = Grouping))
scale_color_manual(values = c(Group1 = "blue", Group2 = "red")))
The only way I am able to achieve what I want is with the really bad solution demonstrated below...
### Dirty Solution
temporary <- example_data[as.Date("2020-10-01") == example_data$Date,]
temporary$Grouping <- "Group2"
example_data <- rbind(example_data,temporary)
print(ggplot(example_data,aes(x = Date, y = Series))
geom_line(aes(color = Grouping))
geom_point(aes(color = Grouping))
scale_color_manual(values = c(Group1 = "blue", Group2 = "red")))
Plot generated, which is what I would like to achieve through a better solution:
Is there any way to achieve what I want with ggplot2? I wasn't able to find a better solution.
CodePudding user response:
library(ggplot2); library(dplyr)
ggplot(example_data,aes(x = Date, y = Series))
# use lag to connect backwards, lead to connect forwards
geom_segment(aes(color = Grouping, xend = lag(Date), yend = lag(Series)))
geom_point(aes(color = Grouping))
scale_color_manual(values = c(Group1 = "blue", Group2 = "red"))