【问题标题】:How to add gaussian curve to histogram created with qplot?如何将高斯曲线添加到使用 qplot 创建的直方图?
【发布时间】:2011-11-03 04:44:03
【问题描述】:

我的问题可能类似于Fitting a density curve to a histogram in R。使用 qplot 我用这个命令创建了 7 个直方图:

 (qplot(V1, data=data, binwidth=10, facets=V2~.)   

对于每个切片,我想添加一条拟合高斯曲线。当我尝试使用lines() 方法时,出现错误:

Error in plot.xy(xy.coords(x, y), type = type, ...) : 
plot.new has not been called yet

正确执行的命令是什么?

【问题讨论】:

  • 您不能将基本图形函数(lines() 等)与 gpplot2lattice 包使用的网格图形混合。跨度>

标签: r histogram ggplot2


【解决方案1】:

你试过stat_function吗?

+ stat_function(fun = dnorm)

您可能希望使用aes(y = ..density..) 绘制直方图,以便绘制密度值而不是计数。

this 问题中可以找到很多有用的信息,包括一些关于在不同方面绘制不同正态曲线的建议。

这里有一些例子:

dat <- data.frame(x = c(rnorm(100),rnorm(100,2,0.5)), 
                  a = rep(letters[1:2],each = 100))

在每个面上叠加一个法线密度:

ggplot(data = dat,aes(x = x)) + 
  facet_wrap(~a) + 
    geom_histogram(aes(y = ..density..)) + 
    stat_function(fun = dnorm, colour = "red")

根据我链接到的问题,使用不同的正态曲线创建一个单独的数据框:

grid <- with(dat, seq(min(x), max(x), length = 100))
normaldens <- ddply(dat, "a", function(df) {
  data.frame( 
    predicted = grid,
    density = dnorm(grid, mean(df$x), sd(df$x))
  )
})

并使用geom_line 分别绘制它们:

ggplot(data = dat,aes(x = x)) + 
    facet_wrap(~a) + 
    geom_histogram(aes(y = ..density..)) + 
    geom_line(data = normaldens, aes(x = predicted, y = density), colour = "red")

【讨论】:

  • 我是 R 的初学者,用了几天。我去看看,谢谢提示!
【解决方案2】:

ggplot2 使用与基本图形不同的图形范例。 (虽然你可以使用grid 图形,但最好的方法是在绘图中添加一个新的stat_function 层。ggplot2 代码如下。

请注意,我无法使用 qplot 进行此操作,但转换到 ggplot 相当简单,最重要的区别是您的数据必须在 data.frame格式。

还要注意 y 美学 aes=aes(y=..density..)) 的显式映射 - 这有点不寻常,但会将 stat_function 结果映射到数据:

library(ggplot2)
data <- data.frame(V1 <- rnorm(700), V2=sample(LETTERS[1:7], 700, replace=TRUE))
ggplot(data, aes(x=V1)) + 
  stat_bin(aes(y=..density..)) + 
  stat_function(fun=dnorm) + 
  facet_grid(V2~.)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 2020-07-03
    相关资源
    最近更新 更多