1
votes

I have built a simple boxplot using ggplot, and I am trying to add an additional theoretical data-point - 'theoretical' in the sense that it did not form part of the original boxplot, but is linked to another dataset I would like to make a comparison to...

Here is my boxplot at present with some dummy data.

# 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)

Current Plot

If I had the below array, where each value represents a theoretical data-point for each condition from a different distribution, how would I include that data-point on the above plot (with a different plot character)?

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)
1

1 Answers

2
votes

You can do this by saving the original ggplot object in a variable and then adding additional layers via "+" later on.

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)