如何将线图与密度图叠加?(R,GG2)
嗨,如何在一个图形中重叠以下曲线?谢谢你的帮助。谢谢大家!如何将线图与密度图叠加?(R,GG2),r,ggplot2,R,Ggplot2,嗨,如何在一个图形中重叠以下曲线?谢谢你的帮助。谢谢大家! library(ggplot2) x = -10:10 y = dnorm(x, mean=0, sd=3) df.norm = data.frame('x'=x, 'y'=y) ggplot(data=df.norm, aes(x=x, y=y)) + geom_line() + geom_point() random = data.frame('x'=rnorm(1000, mean = 0,
library(ggplot2)
x = -10:10
y = dnorm(x, mean=0, sd=3)
df.norm = data.frame('x'=x, 'y'=y)
ggplot(data=df.norm, aes(x=x, y=y)) +
geom_line() +
geom_point()
random = data.frame('x'=rnorm(1000, mean = 0, sd = 3))
ggplot(random, aes(x=x)) +
geom_density(size=1)
我尝试了以下方法,但没有成功
ggplot(data=df.norm, aes(x=x, y=y)) +
geom_line() +
geom_point() +
geom_density(random, aes(x=x), size=1)
ggplot2 ggplot2中更简洁的版本,使用参数
inherit.aes=FALSE
insidegeom_density
覆盖前两层中使用的默认美学
library(ggplot2)
set.seed(2017)
x = -10:10
y = dnorm(x, mean = 0, sd = 3)
df.norm = data.frame('x' = x, 'y' = y)
random = data.frame('x' = rnorm(1000, mean = 0, sd = 3))
ggplot(data = df.norm, aes(x = x, y = y)) +
geom_line() +
geom_point() +
geom_density(data = random,
aes(x = x),
inherit.aes = FALSE,
size = 1)
基础
使scoa提供的解决方案适应基本包:
plot(df.norm, type = "l", bty = "n", las = 1)
points(df.norm, pch= 19)
lines(density(random$x), lwd = 2)
为密度曲线添加图例和不同颜色:
plot(df.norm, type = "l", bty="n", las = 1)
points(df.norm, pch= 19)
lines(density(random$x), lwd =2, col = 'orange')
legend(x = "topleft",
c("df.norm", "Density plot"),
col = c("black", "orange"),
lwd = c(2, 2),
bty = "n")
你好@scoa非常感谢!我能再问一个问题吗?如何添加手动控制的图例?我试过了,但没用
ggplot()+geom_线(数据=df.norm,aes(x=x,y=y),COLOR='red')+geom_点(数据=df.norm,aes(x=x,y=y),COLOR='red')+geom_密度(数据=random,aes(x=x),尺寸=1,COLOURE='blue')比例_颜色_离散(名称=“分布”,标签=c(“计算的”,“模拟”)
再次感谢!只需在aes()
中添加颜色语句:ggplot()+geom_线(data=df.norm,aes(x=x,y=y,color=“red”)+geom_点(data=df.norm,aes(x=x,y=y,color='red'))+geom_密度(data=random,aes(x=x,color='blue'),size=1)+比例_颜色离散(name=“distribution”,labels=c('computed','simulations'))
谢谢@mpalanco!这绝对有用。我的ggplot2经常崩溃Rstudio…你如何添加图例?太好了@我编辑了我的答案,包括一个传说。您可以使用许多参数和选项。检查文档,键入?图例太好了!非常感谢@mpalanco!
plot(df.norm, type = "l", bty="n", las = 1)
points(df.norm, pch= 19)
lines(density(random$x), lwd =2, col = 'orange')
legend(x = "topleft",
c("df.norm", "Density plot"),
col = c("black", "orange"),
lwd = c(2, 2),
bty = "n")