Line in R plot should start at a different timepoint

做~自己de王妃 提交于 2020-01-15 12:32:29

问题


I have the following example data set:

date<-c(1,2,3,4,5,6,7,8)
valuex<-c(2,1,2,1,2,3,4,2)
valuey<-c(2,3,4,5,6)

now I plot the date and the valuex variable:

plot(date,valuex,type="l")

now, I want to add a line of the valuey variable, but it should start with the 4th day, so not at the beginning, therefore I add NA values:

valuexmod<-c(rep(NA,3),valuex)

and I add the line with:

lines(date,valuexmod,type="l",col="red")

But this does not work? R ignores the NA values and the valuexmod line starts with the first day, but it should start with th 4th day?


回答1:


Given that date and valuex have the same length, I am assuming that you have a typo above.

Try this instead:

date <- c(1, 2, 3, 4, 5, 6, 7, 8)
valuex <- c(2, 1, 2, 1, 2, 3, 4, 2)
valuey <- c(2, 3, 4, 5, 6)
valueymod <- c(rep(NA, 3), valuey)

plot(date, valuex, type = "l", ylim = range(c(valuex, valuey)))
lines(date, valueymod, type = "l", col = "red")

Here's the resulting plot:

Related to your question is a point made in help("lines")...

The coordinates can contain NA values. If a point contains NA in either its x or y value, it is omitted from the plot, and lines are not drawn to or from such points. Thus missing values can be used to achieve breaks in lines.



来源:https://stackoverflow.com/questions/16877479/line-in-r-plot-should-start-at-a-different-timepoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!