从一个数据集中以两个Y自动化多个图/图

时间:2019-05-21 15:59:13

标签: r for-loop ggplot2

我试图用两个Y变量绘制34个相对于时间的曲线图。我的数据集结构如下:X Y1A Y2A Y1B Y2B。 。 。 Y1n Y2n

我可以简单地要求ggplot绘制所需的列来单独绘制。但是,我在5个数据集中每个都有34个图,因此自动化此操作将很有用。我真的对如何构造语言以完成我想做的事情感到困惑。 (新用户)。我不擅长循环,甚至不知道这是否是我要使用的正确代码结构。我看过apply函数,但这些函数似乎并没有实现我想要的功能,因为我不是想操纵我的数据,而只是一次绘制所有图形。

我还没有尝试过melt,但是我再次陷入了如何一次创建两行的困境。我是否应该为自己的栏命名不同/更容易实现自动化。

我已经搜索了几个小时,却没有找到能完全回答我问题的信息。


df <- matrix( c( 1,   0.011,    0.002,     0.007,      0.002,
              2,   0.011,      NA,   0.007, NA,
              3,   0.010,    0.002,     0.007,      0.002,
              4,   0.010,      NA,       0.007, NA, 
              5,   0.010,       NA,      0.006, NA, 
              6,   0.010,    0.002,    0.006,       0.002
              ), nrow = 6, ncol= 5, byrow= TRUE) 
colnames(df)<- c("time", "prefish1",  "obsfish1",  "prefish2",  "obsfish2")
biomass<-as.data.frame(df)
for (i in biomass[2]) {   
}
for (k in biomass[3]) {

}
}  ##this will call just columns 2 and 3 as a pair.##
ggplot(biomass, aes(x= time)) +
  geom_line(aes(y=i)) +
  geom_point(aes(y=k)) +
  ggtitle(i) + ylab("biomass t/km2") + 
  ##I would also like to title them using the header one of the column pairs## 
  theme_classic()

编辑 我刚刚尝试过:

pre<- biomass[+c(2,4)] 
obs<- biomass[+c(3,5)] 
for(i in 1:NCOL(pre)){
}
  for(k in 1:NCOL(obs)){
    plot(biomass$time, pre[,i], type= "l", xlab= "time", ylab ="biomass t/km2")
    par(new= TRUE)
    plot(biomass$time, obs[,k], type = "p", main = paste("Fit", names(obs)[k]), xlab= "time", ylab ="biomass t/km2")

  }

但是这里有些问题,我希望每一对点和线都在同一个图中。

预期结果应为34个样地。 -或在此示例中为两个单独的图。

2 个答案:

答案 0 :(得分:1)

分面方法可行吗,还是您想要单独的输出文件?

在ggplot中执行此操作的最常见方法是将单独的行放入各个方面。为此,我们需要在将数据输入ggplot之前对其进行重塑:我们可以有一对列,而不是为每个图在数据中包含单独的成对的列,而用另一列(下面的num)指定每行与哪个图相关。然后,我们可以使用该num变量来映射到构面。 (我们也可以使用相同的准备来完成第二项任务...)

library(tidyr)   # Useful for reshaping the data
library(ggplot2)

biomass %>%
  # Gather data into long format
  gather(column, value, -time) %>%
  # Separate the number of graph from the type of column
  separate(column, c("var", "num"), sep = -1) %>%
  # Put the two types of column back into separate columns
  spread(var, value) %>%


  ggplot(aes(x= time, group = num)) +
  geom_line(aes(y = prefish)) +
  geom_point(aes(y= obsfish)) +
  facet_wrap(~num) +
  ylab("biomass t/km2") + 
  ##I would also like to title them using the header one of the column pairs## 
  theme_classic()

enter image description here

答案 1 :(得分:1)

另一个选项:构建用于绘图的功能。然后创建两个名称向量,同时循环它们,传递给新创建的函数并将结果保存在列表中。之后,使用HttpUtility.UrlEncode将所有地块组合在一起

plot_grid

reprex package(v0.3.0)于2019-05-21创建

相关问题