如何在R中使用ggplot2将线图与密度图叠加?

3

你好,在一个图表中如何将以下曲线重叠显示?非常感谢您的帮助。谢谢!

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)
2个回答

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

enter image description here


你好 @scoa,非常感谢!我可以问一个进一步的问题吗?如何添加手动控制的图例?我尝试了这个但它没有起作用... ggplot() + geom_line(data=df.norm, aes(x=x, y=y), colour='red') + geom_point(data=df.norm, aes(x=x, y=y), colour='red') + geom_density(data=random, aes(x=x), size=1, colour='blue') scale_colour_discrete(name ="distribution", labels=c('calculated', 'simulations')) 再次感谢! - YJZ
只需在 aes() 内添加颜色语句即可:ggplot() + geom_line(data=df.norm, aes(x=x, y=y,colour="red")) + geom_point(data=df.norm, aes(x=x, y=y, colour='red')) + geom_density(data=random, aes(x=x, colour='blue'), size=1) + scale_colour_discrete(name ="分布", labels=c('计算', '模拟')) - scoa

1

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.

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)

enter image description here Base

Adapting the solution provided by scoa to the base package:

plot(df.norm, type = "l", bty = "n", las = 1)
points(df.norm, pch= 19)
lines(density(random$x), lwd = 2)

enter image description here

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

enter image description here


感谢 @mpalanco!这真的很有用。我的 ggplot2 经常会导致 Rstudio 崩溃......请问如何添加图例? - YJZ
太好了!@Y Zhang,我编辑了我的回答并包含了一个图例。有许多参数和选项可供调整。请查看文档并键入“?legend”。 - mpalanco
太好了!非常感谢 @mpalanco! - YJZ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接