简体   繁体   中英

Drawing a line between points on ggplot2 R

My graph shown below will create a simple point scatter graph. I am trying to add a line between points, (3,45)-(4,40), and then a seperate line between points (2,108)-(3,45)-(3,118)-(4,91)-(4,104), and another between (3,45)-(4,40).

I think it has to do with adding more grouping and the a geom_line. However, I am a bit stuck.

Any help would be great.

x<-c(2,3,4,3,4,4)
w<-c(108,114,104,45,91,40)
wts<-data.frame(x,w)
h <- ggplot(data=wts, aes(x,w))
h <- h + geom_point(colour="blue")
h <- h + labs(title="Breaches",x = "Quarter", y= "Number of Breaches")
h<-h + theme_minimal()
h<-h + xlim(1,5)
h<-h + ylim(0,120)
h

One way to do it is to provide new data to subsequent calls to geom_path . Since you're talking about connecting points in the original frame, I don't think it's necessary to make a new frame, just index which columns we want. One nice thing (with ggplot2 ) here is that the aesthetics ( aes(x,w) ) are unchanged (though updating them along with data= is not a problem).

h +
  geom_path(data=wts[c(4,6),], color="blue") +
  geom_path(data=wts[c(1,4,2,5,3),], color="red")

I think you mis-typed one of your coordinates, should (3,118) be (3,114) ? If not, then just generate a new frame and include that instead.

样地

Also, since you include at least one point in both lines, I don't think it can be easily resolved with grouping. For that, I'm inferring that you would define a third variable assigning some points to specific groups. You can get around that by duplicating the offending points, as in below. You'll also need to consider the order of points:

wts2 <- rbind(wts, wts[4,])
wts2$grp <- c(2,2,2,2,2,1,1)
wts2$ord <- c(1,4,2,5,3,6,7)
# original plot, just changing wts for wts2[wts2$ord,]
h <- ggplot(data=wts2[wts2$ord,], aes(x,w)) +
  geom_point(colour="blue") + 
  labs(title="Breaches",x = "Quarter", y= "Number of Breaches") +
  theme_minimal() +
  xlim(1,5) + ylim(0,120)
# an alternative to my first answer
h + geom_path(aes(group = grp, color = factor(grp)))

样地2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM