Thomas Thomas - 3 years ago 109
R Question

Connect grouped points by line in ggplot2

I'm trying to connect each blue point with its corresponding red point per group. However, I have trouble using

geom_segment
. Thx for help.

repl <- data.frame(title = c("A", "B", "C", "A", "B", "C"), diff = c(10.06, -1.89, 12.79, 10.06, -1.89, 12.79), id = c(1:6), acc= c(43, 50, 44, 43, 50, 44), variable= c(rep("A", 3), rep("B", 3)), value=c(43,50,44,53,48,56))


ggplot(repl, aes(value, title, y=reorder(title, diff), group=variable, color=variable)) +
geom_point(size=2, shape=8)+
geom_segment(aes(xend=value, x=value, y=title, yend=title), col='gray')


enter image description here

For each group there should be a line connecting the two points on the horizontal, how should I do that?

Answer Source

This should do.

ggplot(repl, aes(x = value, y = reorder(title, diff),
                 group = title, color = variable)) + 
    geom_point(size = 2, shape = 8)+
    geom_line(col = 'gray')

EDIT:

What you want is to connect points by title while coloring them by variable hence the group = title and color = variable aesthetic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download