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

4
  • You mean you want to create 40 separate histograms (for example, one on each page of a PDF?) Commented Sep 16, 2014 at 0: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). Commented Sep 16, 2014 at 0:38
  • This question and answers may be useful to you (plots by group using lists). Commented Sep 16, 2014 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 :) Commented Sep 16, 2014 at 23:13

1 Answer 1

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...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.