1

I am plotting a series of point that are grouped by two factors. I would like to add lines within one group across the other and within the x value (across the position-dodge distance) to visually highlight trends within the data.

geom_line(), geom_segment(), and geom_path() all seem to plot only to the actual x value rather than the position-dodge place of the data points. Is there a way to add a line connecting points within the x value?

Here is a structurally analogous sample:

# Create a sample data set
d <- data.frame(expand.grid(x=letters[1:3], 
                g1=factor(1:2), 
                g2=factor(1:2)),      
                y=rnorm(12))

# Load ggplot2
library(ggplot2)

# Define position dodge
pd <- position_dodge(0.75)

# Define the plot
p <- ggplot(d, aes(x=x, y=y, colour=g1, group=interaction(g1,g2))) +
     geom_point(aes(shape = factor(g2)), position=pd) +
     geom_line()

# Look at the figure
p

# How to plot the line instead across g1, within g2, and within x?
psommers
  • 13
  • 1
  • 3
  • 3
    Add `position = pd` to the `geom_line()` call? – Axeman Dec 06 '15 at 20:07
  • This is not exactly what I am trying to do; I would want to connect the two circles left of "a" with a line, and the two triangles right of "a" with a line. Then connect the two circles left of "b" with a line and the two triangles right of "b" with a line. For the moment I have just used a different sort of figure all together, but if anyone knows how to draw lines between points within groups in "a", within groups in "b", and within groups in "c", that would be great! – psommers Jan 26 '16 at 19:35
  • Don't forget to accept the answer if it solves your issue. That way other can know that the issue is closed. – Eric Fail Jan 26 '16 at 19:46

1 Answers1

1

Simply trying to close this question (@Axeman please feel free to take over my answer).

p <- ggplot(d, aes(x=x, y=y, colour=g1, group=interaction(g1,g2))) +
     geom_point(aes(shape = factor(g2)), position=pd) +
     geom_line(position = pd)

# Look at the figure
p

enter image description here

Eric Fail
  • 8,191
  • 8
  • 72
  • 128