Skip to content
Prev 313463 / 398502 Next

ggplot: geom_line with only pairs of points connected

Dear list,

I've been using plotmeans {gplots} a lot before, and found the
"connect" argument to be quite useful.
I've moved to ggplot for several reasons, but would still like to
connect lines conditionally, somehow.
Is it possible to do?

Small example:

df <- data.frame(cat=LETTERS[1:4],num=rnorm(4))
ggplot(df, aes(x=cat, y=num)) + geom_point()  +
geom_line(aes(x=as.numeric(cat), y=num))

In this plot, I would like to be able to make the second line (the one
between B and C) not be there.

What I've come up with is this (instead using geom_segment):

df <- data.frame(cat=LETTERS[1:4],num=rnorm(4))
dfdf <-cbind(df[seq(from=1,by=2,along.with=df),],df[seq(from=2,by=2,along.with=df),])
names(dfdf) <- c("cat","num","cat2","num2")
ggplot(df, aes(x=cat, y=num)) + geom_point()  +
geom_segment(aes(x=cat,xend=cat2,y=num,yend=num2),data=dfdf)

Hoewever, in a more extended example (where df is more complex and
also contains factors used for grouping and faceting) this becomes a
bit cumbersome.

Is there a better way to do this?

/Fredrik

--
"Life is like a trumpet - if you don't put anything into it, you don't
get anything out of it."