R语言 从{ggdist}包旋转半小提琴

ulydmbyx  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(145)

对于此数据:

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

我正在用ggdist包中的半小提琴绘制一个雨云图:

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
  )

结果是这样的:

我如何旋转左半小提琴到相应箱线图的左侧?我尝试使用justification = c(0.2, -0.2),但抛出错误。

slmsl1lt

slmsl1lt1#

使用ifelse以及justificationside美学,您可以执行以下操作:

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
  )

相关问题