[英]how to overlay a line plot with a density plot? (R, ggplot2)
Hi how do I overlap the following curves in one graph? 您好如何在一个图表中重叠以下曲线? Any help's appreciated.
任何帮助表示赞赏。 Thank you!
谢谢!
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)
I tried the following and it didn't work 我尝试了以下内容,但没有奏效
ggplot(data=df.norm, aes(x=x, y=y)) +
geom_line() +
geom_point() +
geom_density(random, aes(x=x), size=1)
library(ggplot2)
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() +
geom_line(data=df.norm, aes(x=x, y=y)) +
geom_point(data=df.norm, aes(x=x, y=y)) +
geom_density(data=random, aes(x=x), size=1)
ggplot2 GGPLOT2
A more concise version in ggplot2 using the argument inherit.aes = FALSE
inside geom_density
to override the default aesthetics used in the previous two layers. 使用参数中GGPLOT2更简洁版本
inherit.aes = FALSE
内部geom_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)
Adapting the solution provided by scoa to the base package: 使scoa提供的解决方案适应基础包:
plot(df.norm, type = "l", bty = "n", las = 1)
points(df.norm, pch= 19)
lines(density(random$x), lwd = 2)
Adding a legend, and a different colour for the density curve: 为密度曲线添加图例和不同颜色:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.