英文:
R Colorize several graphs in different colors in matplot()
问题
我有几张图表我想要着色。
示例代码:
X <- sapply(1:3, \(x) cumsum(rnorm(200)))
col <- sample(2:4, nrow(X), replace = TRUE) |> sort()
plot(X[,1], t="p", ylim = range(X), col = col, pch = 20)
lines(X[,2], t="p", col = col, pch = 20)
lines(X[,3], t="p", col = col, pch = 20)
如何使用matplot
函数完成相同的操作?
我尝试了不同的选项,但从未成功。
matplot(X, t="p", lty=1, col = col, pch = 20)
matplot(X, t="p", lty=1, col = cbind(col, col, col), pch = 20)
英文:
I have several graphs that I want to colorize.
code for exapmle
X <- sapply(1:3,\(x) cumsum(rnorm(200)))
col <- sample(2:4,nrow(X),replace = T) |> sort()
plot(X[,1],t="p",ylim = range(X),col=col,pch=20)
lines(X[,2],t="p",col=col,pch=20)
lines(X[,3],t="p",col=col,pch=20)
How can I do the same using the matplot
function?
I tried different options but never succeeded.
matplot(X,t="p",lty=1,col=col,pch=20)
matplot(X,t="p",lty=1,col=cbind(col,col,col),pch=20)
答案1
得分: 2
这里不清楚为什么要在这里使用matplot
。您完全可以在一行中使用plot
轻松完成相同的操作:
plot(rep(seq(nrow(X)), ncol(X)), X, col = col, pch = 20, xlab = "")
如果出于某种原因您必须使用matplot
,可以这样做:
lapply(1:4, function(x) {
if(x == 1) matplot(X, type = 'n') else {
X[!col %in% x,] <- NA
matplot(X, col = x, add = TRUE, pch = 20)
}
})
英文:
It's not clear why you want to use matplot
here at all. You could easily do the same with plot
in one line:
plot(rep(seq(nrow(X)), ncol(X)), X, col = col, pch = 20, xlab = "")
If for some reason you have to use matplot
, you could do:
lapply(1:4, function(x) {
if(x == 1) matplot(X, type = 'n') else {
X[!col %in% x,] <- NA
matplot(X, col = x, add = TRUE, pch = 20)
}
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论