在图中组合矢量

时间:2017-10-06 19:06:04

标签: r plot

我有3个向量a,b和c

a<-rnorm(10,0,1)
b<-rnorm(5,0,1)
c<-rnorm(5,0,1)

现在我想用

做一个简单的情节
plot(a,type="l")

现在有没有办法将b和c添加到a的情节的尾部(从不同颜色的尾部开始的b和c展位)?

2 个答案:

答案 0 :(得分:1)

例如,您可以将所有向量设置得更大并填充您不希望值显示为NA的位置。

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

答案 1 :(得分:1)

这可能是最简单的解决方案:

a <- rnorm(10, 0, 1)
b <- rnorm(5, 0, 1)
c <- rnorm(5, 0, 1)

在b和c的头部添加NA值并使用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)

enter image description here

和ggplot解决方案 - 它利用melt包中的reshape将数据从宽转换为长,并使用seq_along(a)创建x轴:

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

enter image description here

或者你的意思是:

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)

enter image description here

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

enter image description here

无论您选择哪种绘图解决方案,您仍然需要定义一些值(例如b和c的1:5)没有坐标。