Rotate half-violin from {ggdist} package

175 Views Asked by At

For this data:

set.seed(123)
df <- data.frame(
  ID = 1:50,
  Q = rnorm(50),
  A = rnorm(50,1)
)

I'm drawing a raincloud plot with half-violins from the ggdist package:

library(tidyverse)
library(ggdist)
 
df %>%
  pivot_longer(-ID) %>% 
  ggplot(aes(x = factor(name), y = value, fill = factor(name)))+
  
  # add half-violin
  stat_halfeye(
    # adjust bandwidth
    adjust = 0.5,
    # move to the right
    justification = -0.2,
    # remove the slub interval
    .width = 0,
    point_colour = NA
  )+
  geom_boxplot(
    width = 0.12,
    # removing outliers
    outlier.color = NA,
    alpha = 0.5
  )

The result is this: enter image description here

How can I rotate the left half-violin to the left side of the respective boxplot? I've tried to use justification = c(0.2, -0.2) but that throws an error.

1

There are 1 best solutions below

0
stefan On BEST ANSWER

Using an ifelse and the justification and side aesthetics you could do:

set.seed(123)
df <- data.frame(
  ID = 1:50,
  Q = rnorm(50),
  A = rnorm(50, 1)
)

library(tidyverse)
library(ggdist)

df %>%
  pivot_longer(-ID) %>%
  ggplot(aes(x = factor(name), y = value, fill = factor(name))) +
  stat_halfeye(
    aes(
      justification = ifelse(name == "A", 1.2, -.2),
      side = ifelse(name == "A", "left", "right")
    ),
    adjust = 0.5,
    .width = 0,
    point_colour = NA
  ) +
  geom_boxplot(
    width = 0.12,
    outlier.color = NA,
    alpha = 0.5
  )