Adding a line on histogram

Hi everyone, its my first topic. I got a problem with adding a line with a density function of chi square to my histagram . How can i add that? Im a newbie into r

I have to generate 1000 values of chi square with df=3 and put them on histogram with xlim 0-15, then add a line with a density function with the same df.

Hi, and welcome!

Couple of preliminaries: 1) while your example is simple enough not to be necessary, a reproducible example, called a reprex is usually very helpful to get good answers; 2) if applicable, please see the homework policy.

# load "tidyverse" plotting package
# load data frame enhancement package
# make results reproducible
x <- 1000
# create the random distribution and convert to a tibble
distrib <- enframe(rchisq(x,3))
# crease the base plot object
p <- ggplot(distrib, aes(x = value))
# add command to produce a "faded" histogram and select the number of bins
# then overlay density curve (converted to common axis of count)
p + geom_histogram(fill="black", colour="black", alpha = 0.25, binwidth=0.5) + geom_density(aes(y=0.5*..count..), colour="black", adjust=4) 

Created on 2020-01-10 by the reprex package (v0.3.0)

There are a few problems with your code.

  1. There is no type argument to hist function. It does not make sense.
  2. For lines, the default type is "l" (obviously!!). You don't need to supply it. (this is not a problem, but still wanted to say it)
  3. Your second line of code can not plot a line, because the lengths of both the x and y arguments are 1. It just tries to plot a point, 1000 against dchisq(1000, 3).
  4. Also, your first line of code plots frequencies, and second line (if successful) will try to plot probability densities. So, you can't expect them to be overlapping.

If you want to use base graphics, you can do something like this. You can customise it as you want.

set.seed(seed = 49078)
n <- 1000
x <- rchisq(n = n, df = 3)
hist(x = x, freq = FALSE, xlim = c(0, 15))
lines(x = density(x = x), col = "red")

Hope this helps.


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