R中的图+线的ggplot应该如何等效? [英] How should be a ggplot equivalent of plot + lines in R?

查看:79
本文介绍了R中的图+线的ggplot应该如何等效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

获取

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

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)

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

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

谢谢!

推荐答案

您可以执行以下操作:

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

这篇关于R中的图+线的ggplot应该如何等效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆