1

I'm trying to plot 30 histograms from a data frame

'data.frame':   569 obs. of  32 variables:
 $ ID       : int  842302 842517 84300903 84348301 84358402 843786 844359     84458202 844981 84501001 ...
 $ Diag     : Factor w/ 2 levels "B","M": 2 2 2 2 2 2 2 2 2 2 ...
 $ Radius   : num  5.1 5.84 5.59 3.24 5.76 ...
 $ Text     : num  2.41 4.13 4.94 4.74 3.33 ...
 etc....

I want to group all the attributes by Diag (Malign or Benign cancer) and save them in a file as a multiplot (30 individual histograms) together.

But, when I do it my way (iterating over the columns) the ggplot seems to keep the old data somehow and it does not change according to the current column, unless I do it manually.

This is my graphing loop that tries to save each plot in a list:

graph_att<-function(to=10){
  plots<-vector("list",to)
for (i in 1:to){
  dev.next()
  ind<-i+2
  a<-t[1,i] #data.frame with vertical lines I want in the histograms

  g<-ggplot(dataNorm[,c(2,ind)], aes(dataNorm[,ind]))+geom_histogram(aes(fill=Diag), 
  position="identity", colour="#999999", alpha=0.8, binwidth = 0.25)+
  geom_vline(xintercept = a) + 
  scale_fill_manual(values = c("#0072B2", "#E69F00"))

plots[[i]]<-g
rm(g) #trying to make sure its a new plot
}

return(plots)
}

And I am using the multiplot function from http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/ to plot it together. But I'm getting this output, it only changes the vertical line and keeps only one histogram.

I also had an idea to create another data.frame and in each column put $Diag and other variables with it, but do not know how to iterate over them. Because I thought ggplot does not access the columns I want it to.

Thanks for any help.

PS: This is what I get

my output

2
  • aes(dataNorm[,ind]) can't work due to the non-standard evaluation. Maybe try aes_string(names(dataNorm)[ind]). There might be other problems. Provide a reproducible example if you need more help. Commented Feb 22, 2016 at 16:09
  • Oh thanks a lot Roland, thats brilliant! It works perfectly, also it keeps the xlabel as the name of the variable, which is fantastic! Thank you very much. Do you want to post it as a proper answer, so I can click it answered? Commented Feb 22, 2016 at 17:32

1 Answer 1

1

aes does non-standard evaluation. It expects a column name (without quotes) of the data.frame passed to the data argument. You can use aes_string to pass a column name as a character string:

aes_string(names(dataNorm)[ind])
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.