How should be a ggplot equivalent of plot + lines in R? [duplicate]

你。 提交于 2019-12-11 12:25:40

问题


With plot and lines I can make multiple plots overlapped in the same range in R. For example, I can plot the density of a data and then simulate a density distribution in the same plot as follows:

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

obtaining

How can I do the same (introduce both the density of the data mtcars$mpg and the simulation (x,hxn) in the same plot) with ggplot? I would start by

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

but then I do not know how to overlay the x,hxn data.

Thanks!


回答1:


You can do this:

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



来源:https://stackoverflow.com/questions/56558747/how-should-be-a-ggplot-equivalent-of-plot-lines-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!