0

When I add lines() to hist() I get unexplainable crossed lines, could you tell me why? PleaseProblem

x <- 
  rgamma(100, shape = 1, rate = 2)

gamma_distr <-
  fitdistr(x, densfun="gamma")

pdf_gamma <- 
  dgamma(x,
         shape = gamma_distr$estimate[1],
         rate = gamma_distr$estimate[2])

hist(x, 100, freq = FALSE)
lines(x = x, y = pdf_gamma, col="red")
Mr Frog
  • 296
  • 2
  • 16
  • 1
    because `lines` plots in the order that the values are given: `lines(x[order(x)], pdf_gamma[order(x)], col="red")` – rawr Feb 05 '21 at 19:09

1 Answers1

1

Try this:

library(MASS)

x <- rgamma(100, shape = 1, rate = 2)

gamma_distr <- fitdistr(x, densfun="gamma")

hist(x, 100, freq = FALSE)
curve(dgamma(x,
             shape = gamma_distr$estimate[1],
             rate = gamma_distr$estimate[2]), col="red", add = T)
Leonardo
  • 2,439
  • 33
  • 17
  • 31