使用for循环在ggplot2中绘制单个绘图中的多条线 [英] Use for loop to plot multiple lines in single plot with ggplot2

查看:602
本文介绍了使用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))

这篇关于使用for循环在ggplot2中绘制单个绘图中的多条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆