简体   繁体   中英

Combining vectors in plot

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)?

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")

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.

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