【问题标题】:Plot different distributions over histogram with ggplot使用 ggplot 在直方图上绘制不同的分布
【发布时间】:2014-04-28 07:39:50
【问题描述】:

我试图在 R 中绘制一个直方图,并用不同分布的密度覆盖它。它适用于常规直方图,但我无法让它与 ggplot2 包一起使用。

a <- dataset$age

现在遵循我的常规直方图的代码:

Histogram_for_age <- hist(a, prob=T, xlim=c(0,80), ylim=c(0,0.055), main="Histogram for age with density lines", xlab="age") 

mean <- mean(a)
sd <- sd(a)

现在是密度的线/曲线:

lines(density(dataset$age), col="blue", lwd=2, lty=1)
curve(dnorm(x, mean = mean, sd = sd), add = T, col="red", lwd=2, lty=2)
curve(dgamma(x, shape =mean^2/sd^2, scale = sd^2/mean), add = T, col="goldenrod", lwd=2, lty=3) 

还有一个传说:

legend("topright", 
    c("actual distribution of age","gaussian distribution", "gamma distribution"),  
   lty=c(1,2,3),  
   lwd=c(2,2,2),col=c("blue","red","goldenrod"), cex=0.65) 

到目前为止,这是我对 ggplot2 的尝试:

ggplot(dataset, aes(x=age)) + 
geom_histogram(aes(y=..density..),
             colour="black", fill="white") +
geom_density(alpha=.2, fill="lightblue") + stat_function(fun = dgamma, shape=shape)

什么 ggplot2 参数等效于我的 lines() 和 curve() 参数?

【问题讨论】:

    标签: r ggplot2 histogram curve density-plot


    【解决方案1】:

    像这样使用stat_density 而不是geom_density

    ggplot(dataset, aes(x=age)) + 
      geom_histogram(aes(y=..density..), colour="black", fill="white") +
      stat_density(colour="blue", geom="line", position="identity") +
      stat_function(fun=dnorm, args=list(mean=mean(dataset_with_victims$TV_Alter), sd=sd(dataset_with_victims$TV_Alter))) + 
      stat_function(fun=dgamma, args=list(shape=mean(dataset_with_victims$TV_Alter)^2/sd(dataset_with_victims$TV_Alter)^2, scale=sd(dataset_with_victims$TV_Alter)^2/mean(dataset_with_victims$TV_Alter)))
    

    【讨论】:

    • 感谢您的快速回复!关于我上面的伽玛规格,我应该使用什么形状参数?
    • 您可能必须添加geom="point",然后定义形状。你能提供一些example data吗?这让我更容易给出适当的答案。
    • @Cajira 可能意味着函数dgamma 中的shape 参数。您应该将arg=list(shape=...) 添加到stat_function() 的调用中
    • @ilir thanx,我将其包含在我的答案中
    • 谢谢!!! :) 我现在仍然有问题。使用上面的代码,R 返回以下内容:stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
    猜你喜欢
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 2016-11-04
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    相关资源
    最近更新 更多