R 如何在整个小提琴图中延伸线
以Dataframe为例:R 如何在整个小提琴图中延伸线,r,ggplot2,R,Ggplot2,以Dataframe为例: 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",
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_2
中指定的截止值处延伸到单个小提琴的整个宽度
我可以使用geom_段
手动执行此操作,但是否有更好、更具编程性的方法
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
对应的小提琴与该区域重叠。有办法获取这些信息吗?您可以使用geom\u errorbar()
。因此,将第二个块更改为:
df %>%
ggplot(aes(x = id)) +
geom_violin(aes(y = value)) +
geom_errorbar(aes(x = id, ymin = cutoff,ymax = cutoff), color = "red")
为此,我将添加一个geom_errorbar层来绘制df2,并将ymax和ymin设置为相同的y值。
df %>%
ggplot(aes(x = id)) +
geom_violin(aes(y = value)) +
geom_errorbar(aes(x = id, ymin = cutoff,ymax = cutoff), color = "red")