【问题标题】:How should be a ggplot equivalent of plot + lines in R? [duplicate]ggplot 应该如何等效于 R 中的 plot + lines? [复制]
【发布时间】:2019-06-12 09:22:01
【问题描述】:

使用plotlines,我可以在 R 的同一范围内制作多个重叠的图。例如,我可以绘制数据的密度,然后在同一个图中模拟密度分布,如下所示:

plot(density(mtcars$mpg), col = "red")
polygon(density(mtcars$mpg), col = "red")
x <- seq(0, 50, length=1000)
hxn <- dnorm(x,mean=mean(mtcars$mpg), sd = sd(mtcars$mpg))
lines(x,hxn, col="green")

获得

我怎样才能用ggplot 做同样的事情(在同一个图中同时引入数据密度mtcars$mpg 和模拟(x,hxn))? 我会从

library(ggplot2)
ggplot(mtcars,aes(x=mpg))+geom_density(color = "red", fill = "red")+xlim(0,40)

但是我不知道如何覆盖x,hxn 数据。

谢谢!

【问题讨论】:

    标签: r ggplot2 overlay density-plot


    【解决方案1】:

    你可以这样做:

    ggplot(mtcars,aes(x=mpg))+
      geom_density(color = "red", fill = "red")+ 
      xlim(0,40) +
      stat_function(fun = dnorm, args = list(mean = mean(mtcars$mpg), sd = sd(mtcars$mpg)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 2012-09-19
      • 2016-03-28
      • 1970-01-01
      • 2013-04-26
      相关资源
      最近更新 更多