使用ggplot2绘制多条普通曲线而不使用硬编码方法和标准偏差

时间:2017-11-09 14:31:18

标签: r ggplot2 dplyr normal-distribution mapply

我有一个平均值和标准差的向量,我想使用ggplot2在同一个图中绘制与这些平均值和标准差相对应的密度。我使用mapplygather来解决这个问题,但是我认为这些代码行很多很简单:

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)

enter image description here这非常类似于:

Plot multiple normal curves in same plot

事实上,the accepted answer使用了mapply,这样就证实了我在正确的轨道上。但是,我不喜欢这个答案的是它在mapply电话中硬编码手段和标准偏差。这在我的用例中不起作用,因为我从磁盘读取了实际数据(当然,在MRE中我为了简单起见跳过了数据读取部分)。是否可以在不牺牲可读性的情况下简化我的代码,并且无需对mapply调用中的均值和标准差向量进行硬编码?

编辑也许可以通过使用mapply包来避免对mvtnorm的调用,但我不认为这可以提供任何真正的简化。我的大多数代码都是在调用mapply之后发出的。

1 个答案:

答案 0 :(得分:2)

您可以使用purrr::pmap_df保存一些编码,在为每个mean-stdev对构建数据框后自动执行行绑定:

假设my_data的顺序是输入列,或mean, stdev, testtest是字符类。

library(purrr)
tall_df2 <- pmap_df(my_data, ~ data_frame(x = x, test = ..3, density = dnorm(x, ..1, ..2)))

使用数据:

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 = c("Case_01", "Case_02", "Case_03", "Case_04", "Case_05", "Case_06"), 
                      stringsAsFactors = F)

简介:

p <- ggplot(tall_df2, aes(color = factor(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)

给出:

enter image description here