【问题标题】:How to loop a ggplot graph in r如何在r中循环ggplot图
【发布时间】:2015-10-02 11:02:26
【问题描述】:

我有一个如下所示的数据集 (A2);

Year    Gear      Region    Landings.t
1975    Creel     Clyde     3.456
1976    Creel     Clyde     20.531
1977    Creel     Clyde     56.241
1978    Creel     Clyde     43.761
1975    Creel     Shetland  3.456
1976    Creel     Shetland  10.531
1977    Creel     Shetland  46.241
1978    Creel     Shetland  33.761

我正在使用以下代码生成折线图;

ggplot(subset(A2,Region=="Clyde"),aes(x=Year,y=Landings.t,colour=Gear,group=Gear))+
  geom_line()+
  facet_grid(Gear~.,scales='free_y')+
  ggtitle("CLYDE LANDINGS BY GEAR TIME-SERIES")+
  theme(panel.background=element_rect(fill='white',colour='black'))+
  geom_vline(xintercept=1984)

目前我正在为每个不同的区域复制代码,这使得我的脚本很长。我想知道是否有一种方法可以循环代码以遍历每个区域并为每个区域生成一个图?

我已尝试使用上一个问题Loop through a series of qplots 提供的答案,但是当我使用此代码时,它会返回“二进制运算符的非数字参数”错误。

for(Var in names(A2$Region)){
print(ggplot(A2,[,Var],aes(x=Year,y=Landings.t,colour=Gear,group=Gear))+
geom_line()+
facet_grid(Gear~.,scales='free_y')+
ggtitle("CLYDE LANDINGS BY GEAR TIME-SERIES")+
theme(panel.background=element_rect(fill='white',colour='black'))+
geom_vline(xintercept=1984)
}

【问题讨论】:

  • names(A2$Region) 将返回 NULL。你可能想要unique 那里。在A2 之后还有一个,,我认为您想在其中进行子集化。
  • 你缺少print的括号

标签: r loops ggplot2


【解决方案1】:
for(Var in unique(A2$Region)){
  print(
    ggplot(
      subset(A2, Region == Var),
      aes(x = Year, y = Landings.t, colour = Gear, group = Gear)
    )+
    geom_line() +
    facet_grid(Gear ~ ., scales = 'free_y') +
    ggtitle("CLYDE LANDINGS BY GEAR TIME-SERIES") +
    theme(panel.background = element_rect(fill = 'white', colour = 'black'))+
    geom_vline(xintercept = 1984)
  )
}

或使用plyr

library(plyr)
dlply(A2, ~Region, function(x){
    ggplot(
      x,
      aes(x = Year, y = Landings.t, colour = Gear, group = Gear)
    )+
    geom_line() +
    facet_grid(Gear ~ ., scales = 'free_y') +
    ggtitle("CLYDE LANDINGS BY GEAR TIME-SERIES") +
    theme(panel.background = element_rect(fill = 'white', colour = 'black'))+
    geom_vline(xintercept = 1984)
})

plyr 可以轻松地将数据集拆分为多个变量。

dlply(A2, ~Region + Species, function(x){
    ggplot(
      x,
      aes(x = Year, y = Landings.t, colour = Gear, group = Gear)
    )+
    geom_line() +
    facet_grid(Gear ~ ., scales = 'free_y') +
    ggtitle("CLYDE LANDINGS BY GEAR TIME-SERIES") +
    theme(panel.background = element_rect(fill = 'white', colour = 'black'))+
    geom_vline(xintercept = 1984)
})

【讨论】:

  • 有没有办法将该循环放入另一个循环中。我希望每个物种都有相同的地块,但仍然按每个地区。你能有两个背靠背的“for”语句吗?
  • 我正在努力为每个循环情节生成适当的标题;在您给我的第一个答案中,我一直在使用 'ggtitle(paste(Var,"landings by gear time-series")) 工作正常,但是我无法为 plyr 多变量代码找到类似的行。我尝试了许多不同的安排,但我得到了错误:找不到对象'Species.Code',或者它只是给它们所有相同的区域和物种名称。
  • 使用类似ggtitle(paste("fixed title", x$Species[1]))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多