Home > Blockchain >  Plot a vector as a line in r
Plot a vector as a line in r

Time:06-24

I have a vector like this:

vec<-c(NA,1,1,NA,NA,NA,1,NA)

How can I plot it like this: enter image description here

I already have a plot ready, I just want to add a line like above to my current plot. So I tried using line:

line(vec)

But I am having an error. How can I achieve what I want to do?

CodePudding user response:

Something like this?
Note the use of seq_along as x axis coordinates. And of a plot of type "n", meaning no plot, just set the plot area with appropriate width and height.

vec<-c(NA,1,1,NA,NA,NA,1,NA)

plot(seq_along(vec), vec, type = "n", xlab = "", ylab = "")
lines(seq_along(vec), vec, xlab = "", ylab = "")
points(seq_along(vec), vec, pch = 19, xlab = "", ylab = "")

Created on 2022-06-23 by the reprex package (v2.0.1)


The data set cars is probably not the best example since the axis ranges do not match vec's, but here is a plot.

vec <- c(NA,1,1,NA,NA,NA,1,NA)

plot(cars, main = "Stopping Distance versus Speed", xlim = c(0, 25))
lines(seq_along(vec), vec, xlab = "", ylab = "")
points(seq_along(vec), vec, pch = 19, xlab = "", ylab = "")

Created on 2022-06-23 by the reprex package (v2.0.1)

  • Related