Filling certain areas on the geom_violin chart

How to fill a graph geom_violinin ggplot2 with different colors based on fixed cropping?

For example, given the setting:

library(ggplot2)

set.seed(123)
dat <- data.frame(x = rep(1:3,each = 100),
                  y = c(rnorm(100,-1),rnorm(100,0),rnorm(100,1)))
dat$f <- with(dat,ifelse(y >= 0,'Above','Below'))

I would like to take this main plot:

ggplot() + 
    geom_violin(data = dat,aes(x = factor(x),y = y))

and simply each violin is colored differently above and below zero. It’s naive to try comparing aesthetics fill, breaking and evading violin charts:

ggplot() + 
    geom_violin(data = dat,aes(x = factor(x),y = y, fill = f))

what I do not want. I need one violin plot for each value x, but with an interior filled with different colors above and below zero.

+4
source share
1 answer

Here is one way to do it.

library(ggplot2)
library(plyr)

#Data setup
set.seed(123)
dat <- data.frame(x = rep(1:3,each = 100),
                  y = c(rnorm(100,-1),rnorm(100,0),rnorm(100,1)))

ggplot::ggplot_build , :

p <- ggplot() + 
    geom_violin(data = dat,aes(x = factor(x),y = y))
p_build <- ggplot2::ggplot_build(p)$data[[1]]

, geom_violin, , , geom_polygon, .

, :

#This comes directly from the source of geom_violin
p_build <- transform(p_build,
                     xminv = x - violinwidth * (x - xmin),
                     xmaxv = x + violinwidth * (xmax - x))

p_build <- rbind(plyr::arrange(transform(p_build, x = xminv), y),
                 plyr::arrange(transform(p_build, x = xmaxv), -y))

, , .

:

#Add our fill variable
p_build$fill_group <- ifelse(p_build$y >= 0,'Above','Below')
#This is necessary to ensure that instead of trying to draw
# 3 polygons, we're telling ggplot to draw six polygons
p_build$group1 <- with(p_build,interaction(factor(group),factor(fill_group)))

:

#Note the use of the group aesthetic here with our computed version,
# group1
p_fill <- ggplot() + 
    geom_polygon(data = p_build,
                 aes(x = x,y = y,group = group1,fill = fill_group))
p_fill

enter image description here

, x. , x, , , .

+6

All Articles