r - 将自定义线添加到 ggplot/ggplotly 中的 geom_violin

标签 r ggplot2 ggplotly

我对每组数据都有阈值,在绘制 fiddle 图时,我希望这些阈值显示在图中。

相反,线条不受相应组的限制,并且线条仅显示全宽(ggplot)或整个图的一小部分(ggplotly)。

我认为 ggforce 包中的 stat_sina 是前进的方向,但我运气不佳。

我的代码是:

library(tidyverse)
library(plotly)

customLines <- data.frame(name = c('Petal.Length', 'Petal.Width', 'Sepal.Length', 'Sepal.Width'),
                          value = c(2, 1, 5, 3))

iris %>%
  pivot_longer(-Species) %>%
  ggplot(aes(x = name,
             y = value,
             fill = name,
             colour = name,
             group = name)) +
  geom_violin(alpha = 0.3) +
  ggforce::geom_sina() +
  ggforce::stat_sina(data = customLines,
                     aes(x = name,
                         yintercept = value),
                     geom = "hline")
ggplotly()

哪些输出

enter image description here

很明显,这与 fiddle 图不符。

如何让线条仅沿着 fiddle 图的整个宽度并在 fiddle 内?它可能类似于分位数方法,但我也不知道如何以这种格式使用它。

最佳答案

我的解决方案使用ggplot_build来识别 fiddle 图的正确宽度,然后在geom_segment中使用该信息。 ggplotly 也适用于我的解决方案(图未显示)。

library(tidyverse)
customLines <- data.frame(name = c('Petal.Length', 'Petal.Width', 'Sepal.Length', 'Sepal.Width'),
                          value = c(2, 1, 5, 3))

customLines <- customLines %>% 
  mutate(fac = as.integer(factor(name, levels = name)))

p1 <- iris %>%
  pivot_longer(-Species) %>%
  ggplot(aes(x = name,
             y = value,
             fill = name,
             colour = name,
             group = name)) +
  geom_violin(alpha = 0.3)

violin_width <- ggplot_build(p1)$data[[1]] %>% 
  group_by(x) %>% 
  summarize(width = max(violinwidth)) %>% 
  left_join(customLines, by = c("x" = "fac"))

p1 + 
  geom_segment(data = violin_width, 
               aes(x = x - width/2, y = value, xend = x + width/2, yend = value))

创建于 2023 年 5 月 12 日 reprex v2.0.2

关于r - 将自定义线添加到 ggplot/ggplotly 中的 geom_violin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76235431/

相关文章:

r - 插入符号中的 R 中的并行处理

mysql - dbwritetable删除mysql中的自增字段

r - 如何让ggplot线跑到边缘?

r - 使用 ggplot 为轴刻度标签的一部分动态着色

r - 如何在 R 中的 ggplotly 中更改图例位置

r - 生成季节性图,但具有财政年度开始/结束日期

r - 从 Shiny 的发送电子邮件

r - 在列表定义中使用 rlang::sym

r - 在颜色空间中的scale_fill/color中粘贴名称不能循环工作

r - 使用 R 中的 slider 绘制多个数据帧的热图