循环,数据框和ggplot [英] Loops, dataframes and ggplot

查看:68
本文介绍了循环,数据框和ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ggplot在同一页面上显示多个绘图,并且在这里描述的多画面功能: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/ 。我的数据存储在大数据帧中,第一列对应于句点。我想可视化列2:26。我的问题是可重复使用:

I would like to display multiple plots on the same page using ggplot, and the multiplot function described here: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/. My data is stored in a large dataframe with the first column corresponding to period. I want to visualize columns 2:26. My issue is reproducible using:

rawdata1 <- data.frame("Period" = 1:34, "Sample" = sample(x = c(1,2),34, replace = TRUE),"Runif" = runif(n = 34))

直观地,我将使用以下代码:(2:3替换为2:26)

Intuitively, I would use the following code: (With 2:3 replaced with 2:26)

out <- NULL
for (i in 2:3){
  out[[i-1]] <- ggplot(rawdata1, aes("Period", y = value)) + geom_line(aes(x = Period, y = rawdata1[[i]])) + ggtitle(label = colnames(rawdata1)[i])
}

multiplot(plotlist = out, cols = 2)

这样可以绘制多个图形,但是我的问题是每个图形绘制使用同一列的数据(上述示例中的第3列,我的数据集中的第26列)。我很困惑,这是因为我的出列表存储动态存储的y值的ggplot列表。

This succeeds in plotting multiple graphs, however my problem is that each graph that is plotted uses data from the same column (column 3 in the above example, column 26 in my dataset). I've puzzled out that this is because my "out" list stores the ggplot list with the y values stored dynamically.

我的最终值是26,当我从out调用一个项目时,它使用i的当前值来创建图形。所以每个图形都显示使用相同的列。因为我是R的新手,所以我的猜测是我没有正确地管理我的变量。任何帮助将不胜感激

i's final value is 26, and when I call an item from "out", it uses the current value for i to create the graph. So every graph displays using the same column. As I am new to R, so my guess is that I am not managing my variables correctly. Any help would be appreciated

推荐答案

下面找到一个替代方法:使用 fusion 函数从 reshape2 ,然后使用 facet_wrap 进行刻面。

Below you find an alternative: using the melt function from reshape2 and then faceting with facet_wrap.

require(ggplot2)
require(reshape2)
data.melt <- melt(rawdata1, id.var='Period')
ggplot(data.melt, aes(Period, value)) + 
  geom_line() + 
  facet_wrap(~variable, scales='free_y')

如果要使用 multiplot 可以执行以下操作:

If you want to use multiplot instead, you could do the following:

out <- lapply(names(rawdata1)[-1], 
               function(index) ggplot(rawdata1) + 
                 geom_line(aes_string(x = 'Period', y = index)) + 
                 ggtitle(label = index))
multiplot(plotlist = out, cols = 2)

这篇关于循环,数据框和ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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