[R] Lattice Histogram with Normal Curve - Y axis as percentages

Duncan Mackay dulcalma at bigpond.com
Sat May 10 03:19:21 CEST 2014


Just an afterthought if any one really needs to do it again.

The crux of the matter is the different limits in the 2 plot x and y scales.
It may be easier to accomplish this with a prepanel function to get the
limits eg panel.loess  

Duncan


-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of jimdare
Sent: Wednesday, 7 May 2014 14:53
To: r-help at r-project.org
Subject: Re: [R] Lattice Histogram with Normal Curve - Y axis as percentages

Thanks for your help Duncan and Peter!  I ended up using a combination of
your suggestions.  I used Duncan's y.limits ration of two plots with
differing types (percent and density), to provide me with a scale variable. 
I then used this in Peter's dnorm_scaled function and called it using
panel.mathdensity.  See below for my amended code.

Regards,
Jim


x1<-histogram(~rdf[,j]|Year,nint=20, data=rdf,main = i,strip = my.strip,xlab
= j,  
                  type = "density",layout=c(2,1))
  
x2<-histogram(~rdf[,j]|Year,nint=20, data=rdf,main = i,strip = my.strip,xlab
= j,  
                type = "percent",layout=c(2,1))

scale <- x2$y.limits/x1$y.limits
  
dnorm_scaled <- function(...){ scale[1]*dnorm(...)}
  
histogram(~rdf[,j]|Year,nint=20, data=rdf,main = i,strip = my.strip,xlab =
j,  
            type = "percent",layout=c(2,1),
            panel=function(x, ...) {
                            
              panel.histogram(x, ...)
              
              panel.mathdensity(dmath=dnorm_scaled, col="black", 
                                # Add na.rm = TRUE to mean() and sd()
                                args=list(mean=mean(x, na.rm = TRUE),
                                          sd=sd(x, na.rm = TRUE)), ...)

            })



--
View this message in context:
http://r.789695.n4.nabble.com/Lattice-Histogram-with-Normal-Curve-Y-axis-as-
percentages-tp4690000p4690093.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.



More information about the R-help mailing list