0

Consider the following example:

require(ggplot2)

aa <- data.frame(date = runif(3,1,100),Change = runif(3,1,100))

bb <- data.frame(date = runif(3,1,100),Change = runif(3,1,100))

dd <- rbind(aa,bb)
dd$site <- c("aa","aa","aa","bb","bb","bb")

Is it possible to produce 2 figures in the same document where figure 1 should be those sites that correspond to sites == 'aa' and the second figure should be those sites that correspond to sites == 'bb'?

I have tried to generate the figures within a loop but nothing seems to be plotted in the pdf:

nams <- ("aa","bb")

pdf("plots.pdf",width = 6,height = 6, paper='A4',family = "Times")
for (i in 1:2){
  dd2 <- dd[dd$site == nams[i],]

  ggplot(dd,aes(date,Change)) +
    geom_line()
}
dev.off()
Emma Tebbs
  • 1,457
  • 2
  • 17
  • 29
  • Why not use `facets`? `ggplot(dd, aes(date, Change)) + geom_line() + facet_grid(site~.)` – shadow Jan 13 '15 at 13:29
  • This is just an example code, my real data has over 200 sites, thus i need different plots, i cant realistically use facets for that. – Emma Tebbs Jan 13 '15 at 13:46
  • Do you want multiple plots in the same window or a loop to plot each group individually? If the former, [look here](http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)). – Steven Jan 13 '15 at 13:56

1 Answers1

1

You have to use print with the plot to output it:

for (i in 1:2){
  dd2 <- dd[dd$site == nams[i],]

  print(ggplot(dd, aes(date, Change)) +
    geom_line()
  )
}
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168