[R] how to plot the histogram and the curve in the same graph

matthieu dubois matthdub at gmail.com
Tue Oct 21 09:53:31 CEST 2008


leo_wa <kwngai6022 <at> hotmail.com> writes:

> 
> 
> i want to plot the histogram and the curve in the same graph.if i have a set
> of data ,i plot the histogram and also want to see what distribution it
> was.So i want to plot the curve to know what distribution it like.


You will find below an example using only basic plotting functions. 
The created function (called histplot) plots a histogram of the data, 
along with a density kernel estimate of the distribution and 
(if asked by option ncurve=T) the normal distribution 
(with mean and sd computed from the original data). 

Hope this will help

Matthieu


#generating random values to be plotted
dat <- rnorm(100)

#plotting function 
histplot <- function(dat, breaks="Sturges", ncurve=TRUE, ...)
{
	#compute the histogram and density of "dat"
	hdat <- hist(dat, breaks=breaks, plot=F)
	ddat <- density(dat)
	
	#compute the xlim and ylim of the plot
	# i.e. the min and max of the different superimposed 
	#plots (hist, density and normal curves)
	xlim <- range(ddat$x)
	if(ncurve)
	{
		#max of the normal curve		
		maxnorm <- pnorm(mean(dat), mean=mean(dat), sd=sd(dat))
		ylim <- c(0,  max(hdat$density,ddat$y,maxnorm))
	}
	else
	{
		ylim <- c(0,  max(hdat$density,ddat$y))
	}
	
	#plotting 
	plot(hdat,
		freq=F,
		xlim=xlim, ylim=ylim, ...)
	lines(ddat)
	if (ncurve) curve(dnorm(x, mean=mean(dat), sd=(sd(dat))), 
				lty=3, add=TRUE)
}

#usage
histplot(dat)
histplot(dat, ncurve=F)
histplot(dat, col="blue") #arguments are passed to the hist plotting function



More information about the R-help mailing list