7

I am new to ggplot2 and cannot figure out how to draw vertical dotted grey lines between

the points/dots along the x-axis. Here's my example code:

d1 <- runif(10,10,15)

d2 <- runif(10,25,30)

d3 <- rep(1:10,2)

df <- data.frame(x = d3, y = c(d1,d2))

ggplot(df, aes(x=x, y=y)) +

geom_point()
user969113
  • 2,349
  • 10
  • 44
  • 51

3 Answers3

18

If your actual data is structured like the one used for your example, just add geom_line(aes(group = d3)) to the plot.

ggplot(df, aes(x=x, y=y)) +  
 geom_point() + geom_line(aes(group = d3))

enter image description here

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • Thanks for that solution! Easy and works great. Also thanks for the other solutions and to clarify I want the line only between the 2 points and not an extension past the points! – user969113 Sep 04 '12 at 10:08
1

There's definitely better ways than this but:

d1 <- runif(10,10,15)
d2 <- runif(10,25,30)
d3 <- rep(1:10,2)
df <- data.frame(x = d3, y = c(d1,d2))
df$place <- rep(c("min", "max") , each=10)

df_wide <- reshape(df, direction = "wide", v.names="y", timevar="place", idvar="x") 

ggplot(df, aes(x=x, y=y)) +
    geom_segment(aes(x=x, xend=x, y=y.min, yend=y.max), 
        size=1, data=df_wide, colour="grey70", linetype="dotted") +
    geom_point() 

Though I'm not sure what you mean by "along the x axis", maybe you want it to extend top to bottom not just between the points.

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
  • 1
    And if you're new to ggplot I'd recoment these three websites: a) http://had.co.nz/ggplot2/ ; b) http://had.co.nz/ggplot2/docs/ ; c) http://wiki.stdout.org/rcookbook/Graphs/ – Tyler Rinker Sep 03 '12 at 20:19
0

You should be using geom_vline() to do this.

        d1 <- runif(10,10,15)
        d2 <- runif(10,25,30)
        d3 <- rep(1:10,2)
        df <- data.frame(x = d3, y = c(d1,d2))
       ggplot(df, aes(x=x, y=y)) + geom_point() + 
geom_vline(xintercept = df$x, linetype= 3, colour = "#919191")
Maiasaura
  • 32,226
  • 27
  • 104
  • 108