向 ggplot Boxplot 添加额外的点

Adding additional points to ggplot Boxplot

我已经使用 ggplot 构建了一个简单的箱线图,我正在尝试添加一个额外的理论数据点 - 'theoretical' 在某种意义上它不构成原始箱线图的一部分,但链接到我想与另一个数据集进行比较...

这是我目前的箱线图,其中包含一些虚拟数据。

# create a dataset
data <- data.frame(
  name=c( rep("A",10), rep("B",10), rep("B",10), rep("C",10), rep('D', 10)  ),
  value=c( rnorm(10, 10, 3), rnorm(10, 10, 1), rnorm(10, 4, 2), rnorm(10, 6, 2), rnorm(10, 8, 4) )
)

# Plot
data %>%
  ggplot( aes(x=name, y=value, fill=name)) +
  geom_boxplot() +
  scale_fill_viridis(discrete = TRUE, alpha=0.5) +
  geom_jitter(position=position_jitter(0.2), color="black", size=2.0, alpha=0.9, pch=21)

如果我有下面的数组,其中每个值代表来自不同分布的每个条件的理论数据点,我将如何在上面的图中包含该数据点(具有不同的绘图字符)?

A_new <- c(5)
B_new <- c(6)
C_new <- c(10)
D_new <- c(7)

new_vals <- c(A_new, B_new, C_new, D_new)

您可以通过将原始 ggplot 对象保存在一个变量中,然后稍后通过“+”添加额外的图层来实现。

x=data %>%
  ggplot( aes(x=name, y=value, fill=name)) +
  geom_boxplot() +
  geom_jitter(position=position_jitter(0.2), color="black", size=2.0, alpha=0.9, pch=21)

new_data <- data.frame(name=c("A", "B", "C", "D"), value=new_vals)

x + geom_jitter(data=new_data, aes(x=name, y=value, fill=name), position=position_jitter(.2), color="blue", size=1.5, pch=20)