Reputation: 55
I have 3 vectors a,b and c
a<-rnorm(10,0,1)
b<-rnorm(5,0,1)
c<-rnorm(5,0,1)
Now i want to do a simple plot with a
plot(a,type="l")
Now is there a way to add b and c to the tail of the plot of a (booth b and c beginning at the tail of a in different colours)?
Upvotes: 0
Views: 52
Reputation: 19716
Here is probably the simplest solution:
a <- rnorm(10, 0, 1)
b <- rnorm(5, 0, 1)
c <- rnorm(5, 0, 1)
adding NA values at the head of b and c and using matplot:
matplot(cbind(a,c(rep(NA, 5), b), c(rep(NA, 5),c)), type = "l", lty = 1:3, col = 1:3)
legend("topleft", c("a","b", "c"), lty = 1:3, col = 1:3)
and a ggplot solution - it utilizes converting the data from wide to long using melt
from reshape
package and creating the x axis using seq_along(a)
:
library(ggplot2)
ggplot(data = reshape2::melt(data.frame(a,b = c(rep(NA, 5), b), c = c(rep(NA, 5),c),x = seq_along(a)), id.vars = 4))+
geom_line(aes(y = value, x = x, color = variable))+
theme_classic()
Or did you mean:
matplot(cbind(c(a, rep(NA, 5)),c(rep(NA, 9), b), c(rep(NA, 9),c)), type = "l", lty = 1:3, col = 1:3)
legend("topleft", c("a","b", "c"), lty = 1:3, col = 1:3)
ggplot:
ggplot(data = reshape2::melt(data.frame(a = c(a, rep(NA, 4)),b = c(rep(NA, 9), b), c = c(rep(NA, 9), c),x = 1:14), id.vars = 4))+
geom_line(aes(y = value, x = x, color = variable))+
theme_classic()
No matter what plotting solution you choose you would still have to define some values (like 1:5 for b and c) have no coordinates.
Upvotes: 1
Reputation: 2541
You can make all the vectors bigger and fill where you don't want values to appear with NA, for example.
#-- make them all the size 25 (10+5+5), with a having all values in the
# beginning of the vector, b in the middle, c in the end
a <- c(a, rep(NA, 15))
b <- c(rep(NA, 10), b, rep (NA, 5))
c <- c(rep(NA, 15), c)
#-- plot lines
plot(a, type = "l")
lines(b, col = "green")
lines(c, col = "blue")
Upvotes: 1