Reputation: 31
I want to superimpose the PDF of a fitted model following gamma(lambda,k)
with a histogram.
I write :
hist(pressure)
curve(dgamma(x, lambda, k), add=TRUE, col="red")
but I am confused on what the value "x" is. Anyone help please?
Upvotes: 1
Views: 12681
Reputation: 481
truehist()
is from the MASS package and scales the counts to give an estimate of the probability density.
Use the lines()
and density()
functions to overlay a density plot of the weights values on the histogram.
library(MASS)
truehist(mtcars$mpg) #mtcars dataset available in base R
lines(density(mtcars$mpg))
UPDATE:
Onc can draw the same plot using ggplot()
function in ggplot2 library.
library(ggplot2)
ggplot(mtcars, aes(x=mpg)) + geom_histogram(aes(y=..density..), binwidth = 1) + geom_density()
Upvotes: 0
Reputation: 1083
x
is a vector of values of the support for which you want to obtain the value of the PDF. You may want to compare
plot(dgamma(1:20, shape=1))
with the first plot of http://en.wikipedia.org/wiki/Gamma_distribution (parameter 1)
Upvotes: 0
Reputation: 16080
x <- rgamma(100,2,1) #sample
h <- hist(x, plot=FALSE) #generate hist
plot(h, col="grey") #plot hist
xlines <-seq(min(h$breaks),max(h$breaks),length.out=100) #seq of x for pdf
lines(x = xlines,y=dgamma(xlines,2,1) *length(x)*diff(h$breaks)[1])
Upvotes: 6