ggplot 中的两个密度图

Two density plots in ggplot

这真的很基础。仍然希望我能得到你的帮助。我需要叠加两个密度图。第一个是生成的正态密度图,给出了 AAPL 的均值和标准差。 >

x <- seq(-20, 20, length.out = 5113)
normAAPL<-data.frame(x,  f = dnorm(x,mean = meanAAPL, sd = sdAAPL)) %>%
  ggplot(aes(x, f)) +
  geom_line() + 
  stat_function(fun=dnorm, geom="line", col=2, lty=2)+
  ylim(0,0.2)

> meanAAPL
[1] 0.101133
> sdAAPL
[1] 2.461525

接下来是实际分布

dAAPL <-density(oldandnew$AAPL)

其中第20个AAPL数据是

c(-8.810021, 1.45281, -9.051401, 4.628075, -1.774445, -5.25055, 
-6.181806, 10.40407, 3.74302, 3.425328, 2.48944, 6.309463, -1.948374, 
-4.652429, 5.493372, -1.852238, -0.1725783, -7.924, 2.074379, 
-3.431709)

我是否需要将数据合并到一个数据框中以将它们绘制在同一个 ggplot 中?

希望你能帮帮我。

df <- data.frame(x = seq(-20, 20, length.out = 5113),
                 f = dnorm(x))

df2 <- data.frame(x = c(-8.810021, 1.45281, -9.051401, 4.628075, -1.774445, -5.25055, 
                        -6.181806, 10.40407, 3.74302, 3.425328, 2.48944, 6.309463, -1.948374, 
                        -4.652429, 5.493372, -1.852238, -0.1725783, -7.924, 2.074379, 
                        -3.431709))


ggplot() +
  geom_line(data = df, aes(x, f, colour = "Normal")) + 
  geom_density(data = df2, aes(x, colour = "Actual")) +
  ylim(0,0.2) +
  scale_color_manual(name = "Distribution", values = c("Normal" = "Blue", "Actual" = "Red")) +
  theme_minimal() + theme(legend.position = "top", aspect.ratio = 1)

生产: