简体   繁体   中英

how to create several lines plot in r

let's say we have x1=c(6,3,5,4,3,7) and x2=c(5,2,1,7,5,2) , then I want to create a plot like:

在此处输入图片说明

Where X axis is only x1 and x2 and Y axis is the corresponding value. how can I do it in R? thx

plot(1, 1, xlim = c(1,2),
     ylim = range(c(x1, x2)), type = "n", xaxt = "n")
axis(side = 1, at = 1:2, labels = 1:2)
segments(x0 = 1, y0 = x1, x1 = 2, y1 = x2)
points(x = rep(1, length(x1)), y = x1)
points(x = rep(2, length(x2)), y = x2)

在此处输入图片说明

First create an empty plotting surface

plot(0,0, xlim=c(0,1), ylim=range(c(0, x1,x2)), type="n", xaxt="n")
axis(side=1, at=c(0,1), labels=c("x1","x2"))

Then add draw the segments

segments(0, x1, 1, x2)

and optionally points

points(rep(0, length(x1)), x1);
points(rep(1, length(x2)), x2)

If you want to use ggplot, it would make more sense to change your data format though

dd <- data.frame(id=seq_along(x1), x1=x1, x2=x2)
library(ggplot2)
ggplot(dd) + geom_segment(aes(y=x1, yend=x2), x=0, xend=1)

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