将第二个图放入ggplot2 Rstudio中

问题描述 投票:0回答:1

我希望分布f显示在我的图中。

library(ggplot2)
f <- dnorm(x=2)
x <- c(v6$Zwischenankunftszeit)
counts <- c(v6$ZugangFolgeVrg)
df <- data.frame(x=x, counts=counts)

plt <- ggplot(df + f) + geom_bar(aes(x=x, y=counts), stat="identity")
print(plt)
r ggplot2 plot add
1个回答
0
投票

如果要在顶部绘制正态分布的直方图,这是较简单的方法之一:

library(ggplot2)

df <- data.frame(
  x = rnorm(100, mean = 50, sd = 5)
)

ggplot(df, aes(x)) +
  geom_histogram(aes(y = stat(density))) +
  stat_function(fun = dnorm, args = list(mean = mean(df$x), sd = sd(df$x)))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS9VU0xaNEJHLnBuZyJ9” alt =“”>

reprex package(v0.3.0)在2020-05-26创建

如果要以计数单位保持y轴,则必须包装dnorm函数并通过binwidth和观察数进行缩放:

wrap_dnorm <- function(x, mean = 0, sd = 1, binwidth = 1, count = 1) {
  dnorm(x, mean = mean, sd = sd) * binwidth * count
}

ggplot(df, aes(x)) +
  geom_histogram(binwidth = 1) +
  stat_function(fun = wrap_dnorm, 
                args = list(mean = mean(df$x), sd = sd(df$x), 
                            binwidth = 1, count = nrow(df)))
© www.soinside.com 2019 - 2024. All rights reserved.