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.

1
  • See e.g. here. Commented Jul 6, 2017 at 14:25

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.