有一个巧妙的解决方案来自@David Robinson(原始代码来自他的gists,我只做了几个修改)。
他创建了一个新的层(GeomFlatViolin
),该层基于改变小提琴图的宽度:
data <- transform(data,
xmaxv = x,
xminv = x + violinwidth * (xmin - x))
这个层面还有一个width
参数。
示例:
ggplot(dframe, aes(group, val)) +
geom_flat_violin()
![enter image description here](https://istack.dev59.com/dAK7n.webp)
代码:
library(ggplot2)
library(dplyr)
"%||%" <- function(a, b) {
if (!is.null(a)) a else b
}
geom_flat_violin <- function(mapping = NULL, data = NULL, stat = "ydensity",
position = "dodge", trim = TRUE, scale = "area",
show.legend = NA, inherit.aes = TRUE, ...) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomFlatViolin,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
trim = trim,
scale = scale,
...
)
)
}
GeomFlatViolin <-
ggproto("GeomFlatViolin", Geom,
setup_data = function(data, params) {
data$width <- data$width %||%
params$width %||% (resolution(data$x, FALSE) * 0.9)
data %>%
group_by(group) %>%
mutate(ymin = min(y),
ymax = max(y),
xmin = x - width / 2,
xmax = x)
},
draw_group = function(data, panel_scales, coord) {
data <- transform(data,
xmaxv = x,
xminv = x + violinwidth * (xmin - x))
newdata <- rbind(plyr::arrange(transform(data, x = xminv), y),
plyr::arrange(transform(data, x = xmaxv), -y))
newdata <- rbind(newdata, newdata[1,])
ggplot2:::ggname("geom_flat_violin", GeomPolygon$draw_panel(newdata, panel_scales, coord))
},
draw_key = draw_key_polygon,
default_aes = aes(weight = 1, colour = "grey20", fill = "white", size = 0.5,
alpha = NA, linetype = "solid"),
required_aes = c("x", "y")
)
geom_density
和分面。 - Rolandgeom_violin
。 - Roman Luštrik