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()
3
  • Why not use facets? ggplot(dd, aes(date, Change)) + geom_line() + facet_grid(site~.) Commented Jan 13, 2015 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. Commented Jan 13, 2015 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. Commented Jan 13, 2015 at 13:56

1 Answer 1

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()
  )
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.