Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

r - Problems plotting log-likelihood-function with ggplot2

I'm currently trying to plot a log-likelihood-function using ggplot2; the function is defined by

y <- rpois(100, lambda = 3)

f_1 <- function(z) -100*z + sum(log(1/factorial(y)*z^y)).

When trying to calculate values of f_1, everything works fine (e.g. f_1(1) = -316.1308)

But when I try to plot f_1 using ggplot2, an error pops up:

p <- ggplot(data = data.frame(z = 0), mapping = aes(z=z))

p <- p + stat_function(fun = f_1)

error: "longer object length is not a multiple of shorter object length".

How can I fix this error? Thanks

question from:https://stackoverflow.com/questions/65849941/problems-plotting-log-likelihood-function-with-ggplot2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your function must be written to handle length > 1 vectors, because stat_function will pass a vector of values to your function, rather than applying the function to each x-axis value on the plot individually. If you try e.g. f_1(0:10) you get the same warning, confirming this function does not handle length > 1 vectors properly. The problem is with z^y. If z and y are both vectors the behavior is to apply ^ to each element of z and y having the same index. See for example (1:10)^(1:10). Now what happens when you try (1:10)^(1:20)? The warning is telling you the lengths don't match, so the behavior may be unexpected.

You can vectorize your function by just using Vectorize, and this should give the plot you expect

p <- ggplot(data = data.frame(z = 0), mapping = aes(z=z))

p <- p + stat_function(fun = Vectorize(f_1))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...