You can create histograms with the function hist(x</em >) where x is a numeric vector of values to be plotted. The option freq=FALSE plots probability densities instead of frequencies. The option breaks= controls the number of bins.
# Colored Histogram with Different Number of Bins
hist(mtcars$mpg, breaks=12, col="red")技术支持
# Add a Normal Curve (Thanks to Peter Dalgaard)
x <- mtcars$mpg
h<-hist(x, breaks=10, col="red", xlab="Miles Per Gallon",
main="Histogram with Normal Curve")
xfit<-seq(min(x),max(x),length=40)
yfit<-dnorm(xfit,mean=mean(x),sd=sd(x))
yfit <- yfit*diff(h$mids[1:2])*length(x)
lines(xfit, yfit, col="blue", lwd=2)技术支持
Histograms can be a poor method for determining the shape of a distribution because it is so strongly affected by the number of bins used.
Kernel Density Plots
Kernal density plots are usually a much more effective way to view the distribution of a variable. Create the plot using plot(density(x)) where x is a numeric vector.
# Kernel Density Plot
d <- density(mtcars$mpg)# returns the density data
plot(d)# plots the results技术支持
# Filled Density Plot
d <- density(mtcars$mpg)
plot(d, main="Kernel Density of Miles Per Gallon")
polygon(d, col="red", border="blue")技术支持
You can create histograms with the function hist(x</em >) where x is a numeric vector of values to be plotted. The option freq=FALSE plots probability densities instead of frequencies. The option breaks= controls the number of bins.
Histograms can be a poor method for determining the shape of a distribution because it is so strongly affected by the number of bins used.
Kernel Density Plots
Kernal density plots are usually a much more effective way to view the distribution of a variable. Create the plot using plot(density(x)) where x is a numeric vector.
Comparing Groups VIA Kernal Density
The sm.density.compare( ) function in the sm</a ></strong > package allows you to superimpose the kernal density plots of two or more groups. The format is sm.density.compare(x , factor) where x is a numeric vector and factor is the grouping variable.