r - 在ggplot2中使用geom_violin将统计信息传递给geoms

标签 r ggplot2

以下代码:

library(ggplot2)
theData <- data.frame(category <- sample(LETTERS[1:3], 1000, replace = T),
                  value <- rnorm(1000))
thePlot <- ggplot(theData,
              aes(x = category, y = value))
thePlot <- thePlot + geom_violin(fill = "BLACK")
thePlot <- thePlot + coord_flip()
print(thePlot)

将产生这个情节:

violin plot example

但我想实现一种效果,即每个 fiddle 密度的填充(和颜色,理想情况下)的 alpha 值在密度较低的区域降低。也就是说, fiddle 形状在曲线高度小的地方淡入背景中,但在曲线高的地方变暗和不透明。类似这样的效果:

alpha fade example

不幸的是,这些系数图是通过使用非常丑陋的 hack 生成的,并且考虑到新 geom_violin 的灵活性,我想知道是否有一种直接的方法可以在使用 geom_violin 时实现这种 alpha 淡入淡出。

感谢您提供的任何见解!

最佳答案

受到@wch 回答的启发,我决定再次尝试解决这个问题。这和我得到的一样接近:

ggplot(theData, aes(x = category, y = value)) +
    stat_ydensity(geom="segment", aes(xend=..x..+..scaled../2, 
        yend=..y.., alpha=..scaled..), size=2, trim=FALSE) +
    stat_ydensity(geom="segment", aes(xend=..x..-..scaled../2, 
        yend=..y.., alpha=..scaled..), size=2, trim=FALSE) +
    scale_alpha_continuous(range= c(0, 1)) +
    coord_flip() + theme_bw()

enter image description here

ggplot2 的早期版本中,情节显示“带”,但这个问题现在显然已经得到解决。

enter image description here

关于r - 在ggplot2中使用geom_violin将统计信息传递给geoms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10757903/

相关文章:

r - 如何使用 ggplot2 隐藏图例的部分?

r - R中日期直方图的轴颜色

r - dplyr 选择助手的交集

r - 过滤到观察第一个特定值

r - 编写创建列的 R 函数

r - 看起来像 donut 的圆形热图

r - 使用因子使用 ggplot2 创建密度图

r - scale_fill_fermenter() 的自定义调色板

r - 在 R 中,如何将列名打印成向量形式?

R Shiny : Strange behavior of the brush functionality with ggplot2