0

I have a problem with ggplot, especially with stat_function.

I want to plot my distribution, then I want to calculate the Chi-square theoretical distribution and plot it on my actual plot. Without ggplot, I made this with a simple lines()

res.lk <- apply (as.matrix(baf_matrix$res.fst), 2, FUN = function (x) baf_matrix$res.fst*4 / (mean(baf_matrix$res.fst)))

hist(res.lk, probability = T, breaks = 100,main = "LK distribution",     
xlab ="LK") 
x = c(0:as.integer(max(res.lk)))
lines(x,dchisq(x,df=4),lwd=3,col="orange")

Now to make it with ggplot I do this:

Y = as.data.frame(res.lk)

ggplot(data = Y , aes( x = Lk )) + geom_histogram( binwidth=.1, color="black", fill="white" ) + stat_function( fun = dchisq(c(0:as.integer(max(res.lk))),df=4), lwd = 3, col = "orange") + theme_bw()

And I get this error : Warning message: Computation failed in stat_function(): 'what' must be a function or character string

This is what my data looks like : The Lk distribution

I'm trying to fix it but I didn't find how. Can somebody help me please?? Thank you a lot in advance.

Erika
  • 69
  • 8
  • See e.g. [here](https://stackoverflow.com/questions/5688082/ggplot2-overlay-histogram-with-density-curve/34307133#34307133). – Axeman Jul 06 '17 at 14:25

1 Answers1

1

Note: it would really help if you included example data for us to work with.

The argument fun has to be a function. You're passing a vector. Also, because the distribution line only depends on a single value in the data, it'd be better to use annotate:

xseq <- seq(max(Y$res.lk))

ggplot(data = Y, aes(x = Lk)) +
  geom_histogram(binwidth = .1, color="black", fill="white") +
  annotate(
    geom = "line",
    x = xseq,
    y = dchisq(xseq, df = 4),
    width = 3,
    color = "orange"
    ) +
  theme_bw()
Nathan Werth
  • 5,093
  • 18
  • 25