helen.h
helen.h

Reputation: 1023

How to loop a ggplot graph in r

I have a data set (A2) which looks like this;

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

and I am using the following code to generate a line graph;

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)

at the moment I am replicating the code for each different region which is making my script very long. I was wondering if there is a way to loop the code to go through each of the regions and generate a plot for each?

I have tried using the answers available from this previous question Loop through a series of qplots but when I use this code it returns a 'non-numeric argument to binary operator' error.

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)
}

Upvotes: 0

Views: 1928

Answers (1)

Thierry
Thierry

Reputation: 18487

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)
  )
}

or using the plyr package

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 makes it easy to split the dataset along multiple variables.

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)
})

Upvotes: 2

Related Questions