【发布时间】:2024-12-19 14:50:02
【问题描述】:
我有一个均值和标准差向量,我想使用ggplot2 在同一个图中绘制与这些均值和标准差对应的密度。我使用mapply 和gather 来解决这个问题,但是对于我认为应该是微不足道的事情,它的代码行相当多:
library(dplyr)
library(tidyr)
library(ggplot2)
# generate data
my_data <- data.frame(mean = c(0.032, 0.04, 0.038, 0.113, 0.105, 0.111),
stdev = c(0.009, 0.01, 0.01, 0.005, 0.014, 0.006),
test = factor(c("Case_01", "Case_02", "Case_03", "Case_04",
"Case_05", "Case_06")))
# points at which to evaluate the Gaussian densities
x <- seq(-0.05, 0.2, by = 0.001)
# build list of Gaussian density vectors based on means and standard deviations
pdfs <- mapply(dnorm, mean = my_data$mean, sd = my_data$stdev, MoreArgs = list(x = x),
SIMPLIFY = FALSE)
# add group names
names(pdfs) <- my_data$test
# convert list to dataframe
pdfs <- do.call(cbind.data.frame, pdfs)
pdfs$x <- x
# convert dataframe to tall format
tall_df <- gather(pdfs, test, density, -x)
# build plot
p <- ggplot(tall_df, aes(color = test, x = x, y = density)) +
geom_line() +
geom_segment(data = my_data, aes(color = test, x = mean, y = 0,
xend = mean, yend = 100), linetype = "dashed") +
coord_cartesian(ylim = c(-1, 100))
print(p)
Plot multiple normal curves in same plot
事实上,the accepted answer 使用了mapply,这证实了我走在正确的轨道上。但是,我不喜欢这个答案是它硬编码了mapply 调用中的意思和标准偏差。这在我的用例中不起作用,因为我从磁盘读取了真实数据(当然,在 MRE 中,为了简单起见,我跳过了数据读取部分)。是否可以在不牺牲可读性的情况下简化我的代码,并且无需在 mapply 调用中对均值和标准差向量进行硬编码?
EDIT也许可以通过使用包mvtnorm 来避免调用mapply,但我认为这并不能提供任何真正的简化。我的大部分代码都是在调用 mapply 之后出现的。
【问题讨论】:
标签: r ggplot2 dplyr normal-distribution mapply