我有一个使用以下代码生成的数据框,
x <- c(1:10)
y <- x^3
z <- y-20
s <- z/3
t <- s*6
q <- s*y
x1 <- cbind(x,y,z,s,t,q)
x1 <- data.frame(x1)
因此,数据帧x1具有以下数据,
x y z s t q
1 1 1 -19 -6.333333 -38 -6.333333
2 2 8 -12 -4.000000 -24 -32.000000
3 3 27 7 2.333333 14 63.000000
4 4 64 44 14.666667 88 938.666667
5 5 125 105 35.000000 210 4375.000000
6 6 216 196 65.333333 392 14112.000000
7 7 343 323 107.666667 646 36929.666667
8 8 512 492 164.000000 984 83968.000000
9 9 729 709 236.333333 1418 172287.000000
10 10 1000 980 326.666667 1960 326666.666667
现在,我想在同一图中绘制x与y,z与s和t与q的列,为此,我使用以下代码,
p <- ggplot() +
geom_line(data = x1, aes(x = x1[,1], y = x1[,2], color = "red")) +
geom_line(data = x1, aes(x = x1[,3], y = x1[,4], color = "blue")) +
geom_line(data = x1, aes(x = x1[,5], y = x1[,6], color = "green")) +
xlab('x') +
ylab('y')
尽管上面的代码对于仅6列的数据帧来说可以正常工作,但我想对具有许多列数的数据帧执行相同的操作。例如,如果数据帧中有20列,则应该生成一个单独的图,其中包含col 1 vs 2,col 3 vs 4,col 5 vs 6,依此类推,直到col 19 vs20。为此,我使用以下这段代码,
p <- ggplot() + geom_line(data = x1, aes(x = x1[,1], y = x1[,2], color = "red")) + xlab('x') + ylab('y')
ctr <- 1
for (iz in seq(3, ncol(x1), by = 2))
{
p$ctr <- p + geom_line(data = x1, aes(x = x1[,iz], y = x1[,iz+1], color = "green"))
ctr <- ctr+1
}
因此,这些图应逐步分层,最后一个对象应包含整个图。使用以上代码,每次循环运行时图都会被覆盖,有人可能会指出如何捕获完整数据。我也想为每个情节显示一个图例。
谢谢
如果将数据设置为正确的格式,则不需要循环。您可以基于原始数据帧创建一个长数据帧。
x1_long <- data.frame(x = unlist(x1[c(TRUE, FALSE)]),
y = unlist(x1[c(FALSE, TRUE)]),
ind = gl(ncol(x1) / 2, nrow(x1)))
现在,一个geom_line
命令就足够了:
library(ggplot2)
ggplot(x1_long) +
geom_line(aes(x = x, y = y, colour = ind))
(注意。红线也被绘制,但是其值很小。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句