0

I have a dataset looking like this:

#ID   CWRES
#1    0.90000
#1    0.59034
#1    1.81300
#1    1.42920
#1    0.59194
#2    1.90000
#2    1.09034
#2    2.01300
#2    0.42920
#2    0.19194
#...
#40   1.90000
#40   1.59034
#40   0.81300
#40   0.42920
#40   0.59194

That is one variable (CWRES) and 40 individuals (ID) I want to plot an histogram of every ID in a loop using ggplot. I know how to do it with a "normal" syntax, but I am not able to translate this syntax in ggplot.

Here is the "normal" syntax:

#attach(tab)
#for(i in unique(ID)) { 
#    j = ID==i
#    hist(CWRES,probability = T, ylab="Frequency",xlab=paste(CWRES_label),
#         col="grey90",cex=1,main=paste(paste("ID: #",i,sep="")),nclass=20)
#    lines(
#      density(CWRES,col="blue",lwd=2,lty=1))
#    box()
#    abline(v=mean(CWRES),col="blue",lwd=2)
#    abline(v=quantile(CWRES,0.025),col="blue",lwd=2,lty=2)
#    abline(v=quantile(CWRES,0.50),col="blue",lwd=2,lty=2)
#    abline(v=quantile(CWRES,0.975),col="blue",lwd=2,lty=2)
#}
#detach()

Does anybody know how to translate this in to ggplot syntax?

Thank you very much in advance,

Best regards,

Mario

Mario
  • 21
  • 4
  • You mean you want to create 40 separate histograms (for example, one on each page of a PDF?) – David Robinson Sep 16 '14 at 00:37
  • By the way, the code you provide does not work as you intend it to. You never use the variable `j`, which means that every histogram is exactly the same (using all of CWRES, rather than the subset for that ID). – David Robinson Sep 16 '14 at 00:38
  • [This question and answers](http://stackoverflow.com/questions/19146665/how-subset-a-data-frame-by-a-factor-and-repeat-a-plot-for-each-subset/19147917?noredirect=1#comment39128285_19147917) may be useful to you (plots by group using lists). – aosmith Sep 16 '14 at 16:54
  • You are right David, I should not use j in the loop. Thanks to point this out and for your suggestion. I really appreciate it :) – Mario Sep 16 '14 at 23:13

1 Answers1

3

Would something like this help?

library(ggplot2)
for(i in unique(df$ID)){
  gi <- ggplot(aes(x = CWRES), data = subset(df, ID == i)) +
    geom_histogram()
  ggsave(filename = sprintf('%s.png', i), plot = gi)
}

or wrap it to a function

f.Plotit <- function(varID) {
  subdf = subset(df, ID == varID)
  g1 = ggplot(data = subdf, aes(x = CWRES)) +
    geom_histogram()
  print(g1)
  ggsave(sprintf("%s.png", varID))
}
lapply(unique(df$ID), f.Plotit)

Don't forget to check your working dir getwd() or change it accordingly...

Paulo E. Cardoso
  • 5,778
  • 32
  • 42