【问题标题】:Get second plot into ggplot2 Rstudio在 ggplot2 Rstudio 中获取第二个绘图
【发布时间】:2020-05-26 12:55:35
【问题描述】:

我希望分布 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)

【问题讨论】:

  • 什么是v6 变量?您确定此代码适合您吗?
  • v6 是我的数据集的名称,但仅显示 df 图
  • 查看这篇文章并学习how to ask a Q。以及如何创建minimal reprex 然后回到这里修改你的 Q,否则它被关闭或被否决的风险很高!

标签: r ggplot2 plot add


【解决方案1】:

如果你想在顶部绘制一个正态分布的直方图,这是一种更简单的方法:

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`.

reprex package (v0.3.0) 于 2020 年 5 月 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)))

【讨论】:

  • 非常感谢。剩下的问题是,直方图的数据是两个向量。 x&lt;-c(0,2,4,5,10,30,50) and count&lt;-c(30,55,27,94,1,34,5)x 是我的值,数一下它的数量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-12
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多