[R] par mfrow in "function" problem

Joshua Wiley jwiley.psych at gmail.com
Wed Nov 10 20:38:57 CET 2010


Dear Casper,

This is because you create two histograms, the first with the direct
call to hist(), the second at: h = hist(x).  That is also why even
though you set the xlab and main to be blank in your first one,the
histogram with the normal line added actually was titled.  Normally,
hist() just overwrites the plot in the current device, but since there
are 4 slots in the device (par(mfrow = c(2, 2))), you then saw
multiple histograms.  You can avoid this by setting the plot = FALSE
argument in the histogram you do not want plotted.  Here is how I
would revise it:

par(mfrow=c(2,2))
#############################
myhist=function(x){
       hist(x,xlab="",main="")
       h=hist(x, plot = FALSE)
       xfit=seq(min(x),max(x),length=100)
       yfit=dnorm(xfit,mean(x),sd=sd(x))
       yfit=yfit*diff(h$mids[1:2])*length(x)
       lines(xfit, yfit, col="blue", lwd=2)
}
#############################

## an example
myhist(rnorm(400))


HTH,

Josh

On Wed, Nov 10, 2010 at 11:31 AM, casperyc <casperyc at hotmail.co.uk> wrote:
>
> Hi all,
>
> I defined the following
>
> #############################
> myhist=function(x){
>        hist(x,xlab="",main="")
>        h=hist(x)
>        xfit=seq(min(x),max(x),length=100)
>        yfit=dnorm(xfit,mean(x),sd=sd(x))
>        yfit=yfit*diff(h$mids[1:2])*length(x)
>        lines(xfit, yfit, col="blue", lwd=2)
> }
> #############################
>
> individually, it worked fine
>
> however, if I used
>
> par(mfrow=c(2,2))
>
> each time i run myhist
>
> it produces TWO plots,
>
> one without the 'lines',
> and one with the 'lines'
>
> why is that??
>
> Thanks.
>
> casper
> --
> View this message in context: http://r.789695.n4.nabble.com/par-mfrow-in-function-problem-tp3036745p3036745.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list