1

The following code plots the the data according to age on either the left side (Young) or the right side (Old) of each box.

set.seed(100)
df_data <- expand.grid(group=c("A", "B", "C", "D"), size=c("Small", "Large"), age=c("Young", "Old"), stringsAsFactors=T)
df_data <- df_data[rep(c(1:nrow(df_data)), 10),]
df_data <- cbind(df_data, value=rnorm(nrow(df_data)))

p <- ggplot(data=df_data,
            mapping=aes(x=group, y=value)) +
  geom_boxplot(aes(fill=size),
               outlier.shape=NA) +
  scale_fill_manual(values = c(rgb(240,200,200, maxColorValue=255), rgb(198,210,233, maxColorValue=255))) +
  geom_point(aes(shape=size, color=age),
             position=position_jitterdodge()) +
  scale_shape_manual(values=c(16, 16)) +
  scale_color_manual(values=c("black", "red"))

enter image description here

I am looking at avoiding the separation between the black and red dots within each box, i.e. having both black and red dots "jittering" with respect to the mid-line of each box.

This is how I want the points to be distributed within each box. enter image description here

  • 1
    Sounds like you just want `position=position_jitter()`, but presumably that's not it as you've used `position=position_jitterdodge()`. Can you explain a little more what you're aiming for? – SamR Mar 29 '23 at 15:17

1 Answers1

0

You could group in your geom_point based on the size to have the points jitter in each boxplot, instead of having the jitter on each boxplot within each group. You could adjust the width of the jitter points with jitter.width in position_jitterdodge like this:

library(ggplot2)
p <- ggplot(data=df_data,
            mapping=aes(x=group, y=value)) +
  geom_boxplot(aes(fill=size),
               outlier.shape=NA) +
  scale_fill_manual(values = c(rgb(240,200,200, maxColorValue=255), rgb(198,210,233, maxColorValue=255))) +
  geom_point(aes(shape=size, color=age, group = size),
             position=position_jitterdodge(jitter.width = 0.5)) +
  scale_shape_manual(values=c(16, 16)) +
  scale_color_manual(values=c("black", "red"))
p

Created on 2023-03-29 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53