在 R 中的箱形图旁边绘制垂直正态分布

Plotting a vertical normal distribution next to a box plot in R

我正在尝试绘制箱形图,其中基础数据呈正态分布,并以垂直格式绘制在图旁边:

这是我目前从上传到 R 的 excel sheet 中绘制的图表:

以及与之关联的代码:

set.seed(12345)
library(ggplot2)
library(ggthemes)
library(ggbeeswarm)


#graphing boxplot and quasirandom scatterplot together
ggplot(X8_17_20_R_20_60, aes(Type, Diameter)) + 
  geom_quasirandom(shape=20, fill="gray", color = "gray") +
  geom_boxplot(fill="NA", color = c("red4", "orchid4", "dark green", "blue"), 
               outlier.color = "NA") +
  theme_hc()

一般来说,这在 ggplot2 或 R 中可行吗?或者唯一可行的方法是通过 OrignLab(第一张图片的来源)之类的东西?

您可以使用 gghalves 包执行类似于示例图的操作:

library(gghalves)

n=0.02

ggplot(iris, aes(Species, Sepal.Length)) + 
  geom_half_boxplot(center=TRUE, errorbar.draw=FALSE, 
                    width=0.5, nudge=n) +
  geom_half_violin(side="r", nudge=n) +
  geom_half_dotplot(dotsize=0.5, alpha=0.3, fill="red", 
                    position=position_nudge(x=n, y=0)) +
  theme_hc()

有几种方法可以做到这一点。为了完全控制情节的外观,我只需要计算曲线并绘制它们。以下是一些与您自己的数据相近且同名的示例数据,因此应该可以直接应用:

set.seed(12345)

X8_17_20_R_20_60 <- data.frame(
  Diameter = rnorm(4000, rep(c(41, 40, 42, 40), each = 1000), sd = 6),
  Type = rep(c("AvgFeret", "CalcDiameter", "Feret", "MinFeret"), each = 1000))

现在我们根据从每组中获取的参数创建一个正态分布的小数据框:

df <- do.call(rbind, mapply( function(d, n) {
  y <- seq(min(d), max(d), length.out = 1000)
  data.frame(x = n - 5 * dnorm(y, mean(d), sd(d)) - 0.15, y = y, z = n)
  }, with(X8_17_20_R_20_60, split(Diameter, Type)), 1:4, SIMPLIFY = FALSE))

最后,我们绘制您的图并添加 geom_path 新数据。

library(ggplot2)
library(ggthemes)
library(ggbeeswarm)

ggplot(X8_17_20_R_20_60, aes(Type, Diameter)) + 
  geom_quasirandom(shape = 20, fill = "gray", color = "gray") +
  geom_boxplot(fill="NA", aes(color = Type), outlier.color = "NA") +
  scale_color_manual(values = c("red4", "orchid4", "dark green", "blue")) +
  geom_path(data = df, aes(x = x, y = y, group = z), size = 1) +
  theme_hc()

reprex package (v0.3.0)

于 2020-08-21 创建