问题
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