首页 > 解决方案 > 如何在整个小提琴图上延伸线

问题描述

以数据框为例:

library(tidyverse)
set.seed(123)
df <- data.frame("b" = runif(1000, min = 2, max = 10),
                 "c" = runif(1000, min = 2, max = 10),
                 "d" = runif(1000, min = 2, max = 10))

df_2 <- data.frame(id = c("b", "c", "d"),
                   cutoff = c(5, 3, 5),
                   stringsAsFactors = FALSE)

df <-
  pivot_longer(
    df,
    cols = c("b", "c", "d"),
    names_to = "id",
    values_to = "value"
  ) %>%
  left_join(df_2, by = "id")

我现在可以制作一个小提琴图(或箱线图,同样的问题),上面有一条线:

df %>% 
  ggplot(aes(x = id)) +
  geom_violin(aes(y = value)) +
  geom_line(aes(x = id, y = cutoff, group = 1), color = red)

在此处输入图像描述

我想要的是三条线(不需要连接),每条线都延伸到单个小提琴的整个宽度,在df_2.

我可以使用 手动执行此操作geom_segment,但有更好、更程序化的方式吗?

df %>% 
  ggplot(aes(x = id)) +
  geom_violin(aes(y = value)) +
  geom_segment(aes(x = 0.55, xend = 1.45, y = 5, yend = 5), color = "blue") +
  geom_segment(aes(x = 1.55, xend = 2.45, y = 3, yend = 3), color = "blue") +
  geom_segment(aes(x = 2.55, xend = 3.45, y = 5, yend = 5), color = "blue")

在此处输入图像描述

我知道在某些基本级别上,x 轴按因子级别排序,b= 1,c= 2 等,因此要求与 x = 0.9 相交的线需要指定相应的 y 值。但在另一种意义上,ggplot2清楚地知道(在某种意义上)x = 0.9 以上的区域(即 y 值与 x = 0.9 处的垂直线相交)与因子水平相关,b因为相应的小提琴b与该区域重叠。有没有办法获取这些信息?

标签: rggplot2

解决方案


您可以使用geom_errorbar(). 因此,将您的第二个块更改为:

df %>% 
  ggplot(aes(x = id)) +
  geom_violin(aes(y = value)) +
  geom_errorbar(aes(x = id, ymin = cutoff,ymax = cutoff), color = "red")

推荐阅读