R ggplot2向直方图添加函数

时间:2017-08-17 20:24:11

标签: r ggplot2 statistics

我正在尝试将此函数曲线添加到直方图中。他们个人工作。但是当我试图把它们放在同一个图表上时,这个功能会搞砸......我似乎无法弄清楚如何将它们组合在一起。

# 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和cx具有相同数量的数据点。

# function for curve (alpha and beta are just constants set at 0.5)
fx= function(x){
    (beta^alpha)/((x+beta)^(alpha+1)*gamma(alpha))
}

当geom_histogram或stat_function被注释掉时,图表可以正常工作。

# 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

2 个答案:

答案 0 :(得分:1)

与@Gregor一样,我对您的代码进行了一些更改,图表看起来还不错 我希望它可以帮到你。

set.seed(1)
x <- rgamma(10000,1)
df1 <- data.frame(x= x, cx= c(seq(from= 0.001, to= 10, by= 0.001)))

beta <- alpha <- 0.5
fx <- function(x) {
    print(str(x))
    (beta^alpha)/((x+beta)^(alpha+1)*gamma(alpha))
}

# graph code
h_x <- ggplot(data=df1) +
    geom_histogram(aes(x= x, y= ..density..), binwidth= 0.2, col= "purple", fill= "yellow") +
    stat_function(fun=fx, aes(x=cx), lwd=1) +
    coord_cartesian(xlim= c(0:10)) +
    labs(title= "Figure 03", x="x")
plot(h_x)

enter image description here

答案 1 :(得分:0)

感谢您的帮助!我最终搞清楚了问题......这是因为我的x值有一些大的值(大于100),当我删除这些点时,图表看起来好多了!

但现在我的图表看起来像这样:

graph without a smooth curve

n= 10000
 i= 1
 alpha= 0.5
 beta= 0.5
 x= matrix(data= 5, nrow= n)
 lambda= matrix(data= 1.5, nrow= n)

 while (i < n) {
   x[i+1]= rexp(1, rate= lambda[i])
   lambda[i+1]= (x[i+1]+beta)^(alpha+1)*(lambda[i]^alpha)*exp(-lambda[i]*(x[i+1]+beta))

if ((lambda[i+1] < 0.00001) || (lambda[i+1] > 10)) {
  while ((lambda[i+1] < 0.00001) || (lambda[i+1] > 10)) {
    x[i+1]= rexp(1, rate= lambda[i])
    lambda[i+1]= (x[i+1]+beta)^(alpha+1)*(lambda[i]^alpha)*exp(-lambda[i]*(x[i+1]+beta))
  }
}
i= i+1
}

# data frame:
df4= data.frame(x= x[x<100], cx= c(seq(from= 0.011, to= 10, by= 0.001)))  

# graph (same function (fx) from first post):
h_x= ggplot(data= df4) +
    geom_histogram(aes(x= x, y= ..density..), binwidth= 0.2, col= "purple", fill= "yellow") +
    stat_function(fun= fx) +
    coord_cartesian(xlim= c(0:10)) +
    labs(title= "Figure 03", x= "x")
  plot(h_x)

有没有办法让它变得平滑?我试过scale_x_continuous,但无济于事......