1

这是针对我的问题进行的示例数据(实际上变量的数量很大)

date<-seq(as.Date("2000/1/1"), by = "month", length.out = 12)
v1<-seq(2,32, length.out=12)
v2<-c(11,NA,30,NA,NA,35,NA,40,48,NA,55,64)
v3<-c(5,NA,NA,NA,22,25,NA,30,NA,NA,45,NA)
as.POSIXlt(date, format="%Y/%m/%d")
df<-data.frame(date, v1, v2, v3)

为了随时间同时绘制所有变量,我使用:

matplot(df[,1], df[2:ncol(df)], type='p', pch=2:4, col=2:4)

现在我想通过线连接所有点,但是“matlines”无法插入缺失值的位置。我没有在 'matplot' 中使用 type='b' 因为它只为 v1 绘制连续线(即连续数据)。

但是,一种插值方法是使用“近似”函数。所以我尝试了

matplot(approx(df[,1], df[2:ncol(df)], n= length(df[[1]])), type='p', pch=2:4, col=2:4)

但是 R 抛出一个错误:“ Error in xy.coords(x, y) : 'x' and 'y' lengths differ

现在作为最后的手段,我尝试“lapply”将线条叠加在符号上,但在这种情况下,不同的变量不会显示不同的颜色!

lapply(2:4, function(i) lines(
  approx(df[,1],
         df[[i]], n= length(df[[1]])),
  lty=2, col=2:4))

有没有其他方法可以将变量绘制为单个图中具有不同颜色的线条+符号?

4

2 回答 2

1

这是使用的替代解决方案ggplot

library(reshape2)
library(ggplot2)

# melt the data frame df from wide format (three columns V1-V3 with values on the same measured variable)
# to long format (one column "variable" with three different levels, and one "value" with the measurements)
df2 <- melt(df, id.vars = "date")

# remove rows with missing "value"
df3 <- df2[!is.na(df2$value), ]

# plot value ~ date, coloured by 'variable'
ggplot(data = df3, aes(x = date, y = value, col = variable)) + geom_point() + geom_line()
于 2013-08-25T21:26:35.347 回答
1

如果您在调用(最后一个代码块)中替换col=2:4为,您将在绘图中获得正确颜色的线条。col=ilapply()

with 的错误approx()是不言自明的—— xandy参数需要是向量,并且您正在为y. 每列单独使用approx(),效果很好。

df_approx = matrix(nrow = nrow(df), ncol = 3)
for(i in 2:4) df_approx[,i-1] = approx(df[,1], df[,i], n=length(df[[1]]) )$y
matplot(df[,1], df_approx)
于 2013-08-25T21:16:10.877 回答