From this SO answer I've constructed a geom_point()
with a geom_line()
that connect across NA
s.With the code and data below I get something like this:
I would however like the color to change midway between -1 and 1, and not at the next node (so to speak). I imagine something like this:
How can I do this in a simple way?
Here's the code I've used so far.
df <- data.frame(
x = c(-3, -2, -1, 1, 2, 3, -3, -2, -1, 1, 2, 3),
y = c(2.5, NA, 2, 3, NA, 4, 1.5, 3.5, NA, NA, 2, 1),
typ = factor(c('Before x', 'Before x', 'Before x', 'After x', 'After x',
'After x', 'Before x', 'Before x', 'Before x', 'After x',
'After x', 'After x')),
grp = c(rep(1, 6), rep(2, 6)) ) # df
df$x2 <- with(df, ifelse(x < 0, x+.5, x-.5))
library(ggplot2)
ggplot(df[!is.na(df$y),],
aes(x2, y, group = grp, colour = typ)) +
geom_point() +
geom_line() +
scale_x_continuous(breaks = c(-2.5, -1.5, -.5, 0.5, 1.5, 2.5),
labels = c(-3:-1, 1:3)) +
scale_fill_brewer(palette="Spectral")