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
x=1000
hist(rchisq(x,3),xlim=c(0,15),type="l")
lines(x,dchisq(x,3),xlim=c(0,15),type="l")
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.
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
library(ggplot2)
# load data frame enhancement package
library(tibble)
# make results reproducible
set.seed(42)
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)
There is no type argument to hist function. It does not make sense.
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)
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).
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")