使用for循环在ggplot2中绘制单个绘图中的多条线
I try to plot multiple lines in single plot as follow:
然而,看来 qplot
会在 plot(m)
期间解析 m
>其中 i
是 10
,所以 plot(m)
只生产一条线。
y <- matrix(rnorm(100), 10, 10)
m <- qplot(NULL)
for(i in 1:10) {
m <- m + geom_line(aes(x = 1:10, y = y[,i]))
}
plot(m)
我期望看到的内容类似于:
However, it seems that qplot
will parse m
during plot(m)
where i
is 10
, so plot(m)
produces single line only.
What I expect to see is similar to:
应该包含10个不同的行。
plot(1,1,type='n', ylim=range(y), xlim=c(1,10))
for(i in 1:10) {
lines(1:10, y[,i])
}
是否有 ggplot2
这样做?
which should contain 10 different lines.
ggplot2需要长格式的数据(您可以使用reshape2 :: melt()将其转换)。然后通过一列(这里是Var2)分割线。
Instead of ruuning a loop, you should do this the ggplot2 way. ggplot2 wants the data in the long-format (you can convert it with reshape2::melt()). Then split the lines via a column (here Var2).
y <- matrix(rnorm(100), 10, 10)
require(reshape2)
y_m <- melt(y)
require(ggplot2)
ggplot() +
geom_line(data = y_m, aes(x = Var1, y = value, group = Var2))