[R] ggplot: geom_line with only pairs of points connected

Ista Zahn istazahn at gmail.com
Wed Dec 12 16:06:42 CET 2012


Hi Fredrik,

Here is an alternative:

df <- data.frame(cat=LETTERS[1:4],num=rnorm(4))

df$g <- df$cat
levels(df$g) <- c("G1", "G1", "G2", "G2")

ggplot(df, aes(x=cat, y=num)) + geom_point()  +
geom_line(aes(group=g))

Best,
Ista

On Wed, Dec 12, 2012 at 3:28 AM, Fredrik Karlsson <dargosch at gmail.com> wrote:
> 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."
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list