Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical lines between points with ggplot2

Tags:

r

ggplot2

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()
like image 829
user969113 Avatar asked Sep 03 '12 19:09

user969113


2 Answers

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

like image 78
Sven Hohenstein Avatar answered Oct 02 '22 04:10

Sven Hohenstein


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.

like image 30
Tyler Rinker Avatar answered Oct 02 '22 06:10

Tyler Rinker