I am trying to add this function curve to a histogram. Individually, they work. But when I try to put them on the same graph, the function messes up... I can't seem to figure out how to get them together.
# make dataframe for ggplot (can use random numbers from 0 to 10 to simulate x)
c= data.frame(x= x, cx= c(seq(from= 0.001, to= 10, by= 0.001)))
x and cx have the same number of data points.
# function for curve (alpha and beta are just constants set at 0.5)
fx= function(x){
(beta^alpha)/((x+beta)^(alpha+1)*gamma(alpha))
}
When either the geom_histogram or the stat_function is commented out, the graph works correctly.
# graph code
h_x= ggplot(data= NULL) +
geom_histogram(data= c, aes(x= x, y= ..density..), binwidth= 0.2, col= "purple", fill= "yellow") +
stat_function(fun= fx, data= c, aes(x= cx)) +
coord_cartesian(xlim= c(0:10)) +
labs(title= "Figure 03", x= "x")
plot(h_x)
Curve by itself
;
Histogram and curve together



set.seed(47); cc = data.frame(x= runif(10000, 0, 10), cx = c(seq(from= 0.001, to= 10, by= 0.001)))andfx = function(x, alpha = 0.5, beta = 0.5, gamma = 0.5){ (beta^alpha)/((x+beta)^(alpha+1)*gamma(alpha)) }. (I renamed the dataccbecausecis already the name of the most common function). With those changes to make it run, the graph looks fine. If you still have problems, please edit the code so that the problems can be reproduced. For now I am voting to close as "typo/not reproducible".alpha,beta, orgamma. This is why it is good practice to treat function parameters as arguments rather than having them go out looking for values in the global environment.