Plot a histogram of the values in data and fit a normal density

Hi
How to plot a histogram of the values in data and fit a normal density function in R at the same time. In this plot, hist and probability density curve. I can only do histograms now. Just take the dat1 as an example, thank you for your help in advance.

dat1<-c(9.1,10.7,10.2,14.9,7.4,13.8,9.3,10.6,1.3,2.8,5.8,8.9,9.4,7.3,12.5,18.4,15.0,11.8,13.7,10.2,9.5,7.6,13.6,3.6,3.2,10.2,17.7,6.8,3.5,18.9,15.5,4.9,2.6)
hist(dat1)

Created on 2022-11-01 with reprex v2.0.2

Here is one method.

dat1<-c(9.1,10.7,10.2,14.9,7.4,13.8,9.3,10.6,1.3,2.8,5.8,8.9,9.4,7.3,
        12.5,18.4,15.0,11.8,13.7,10.2,9.5,7.6,13.6,3.6,3.2,10.2,17.7,6.8,
        3.5,18.9,15.5,4.9,2.6)
MU <- mean(dat1)
SD <- sd(dat1)
X <- seq(from=0,to=20,by=0.5)
Y <- dnorm(X,mean=MU,sd=SD)
hist(dat1, freq = FALSE) #freq = FALSE plots the density
lines(X,Y)

Created on 2022-10-31 with reprex v2.0.2

Thank you for your help. One more question, if i set the distribution type, such as Weibull Distribution and others, i need calculate the parameter and the use the line()?

Yes, you have to calculate the parameters for the density function that you want to use. You might find the fitdistr() function from the MASS package helpful. For example, for the normal distribution it could be used like this:

dat1<-c(9.1,10.7,10.2,14.9,7.4,13.8,9.3,10.6,1.3,2.8,5.8,8.9,9.4,7.3,
         12.5,18.4,15.0,11.8,13.7,10.2,9.5,7.6,13.6,3.6,3.2,10.2,17.7,6.8,
         3.5,18.9,15.5,4.9,2.6)
FIT <- MASS::fitdistr(x = dat1, densfun = "normal")
FIT$estimate
    mean       sd 
9.718182 4.689799 
X <- seq(from=0,to=20,by=0.5)
Y <- dnorm(X,mean=FIT$estimate["mean"],sd=FIT$estimate["sd"])
hist(dat1, freq = FALSE) #freq = FALSE plots the density
lines(X,Y)

Check the help section of fitdistr() to see the other distributions it supports.

2 Likes

it works!!!I am appreciative your effort and time in this matter.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.