简体   繁体   中英

how to plot histogram and pdf together in r

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?

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])

带PDF的直方图

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)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM