r - 如何在整个小提琴图上延伸线
问题描述
以数据框为例:
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
与该区域重叠。有没有办法获取这些信息?
解决方案
您可以使用geom_errorbar()
. 因此,将您的第二个块更改为:
df %>%
ggplot(aes(x = id)) +
geom_violin(aes(y = value)) +
geom_errorbar(aes(x = id, ymin = cutoff,ymax = cutoff), color = "red")
推荐阅读
- flutter - Flutter中如何减少AppBar的标题空间
- azure-container-service - Azure 托管 Kubernetes 服务 (AKS) 中的安全性
- xamarin - Xamarin.Forms 任务与目标不匹配
- c++ - 关于全局变量
- artifactory - 如何将基于文本的文件上传到 Artifactory,使其不添加 html-header?
- scroll - VS Code 中的快速文本滚动
- android - Azure 移动应用在后台同步
- inheritance - 我可以避免为从接口派生的类编写样板代码吗?
- c# - Azure 的 .NET Core 数据库连接错误
- javascript - 如何停止为值重复键