R中的图+线的ggplot应该如何等效?

时间:2019-06-12 09:22:01

标签: r ggplot2 overlay density-plot

使用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")

获取 enter image description here

如何使用mtcars$mpg进行相同操作(在同一图中同时引入数据(x,hxn)和模拟ggplot的密度)? 我将从

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

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

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以这样做:

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)))

enter image description here

相关问题