Last active
April 22, 2022 10:09
-
-
Save RaphaelS1/1e5cae1d1321b94c59b5e9e55e8180e5 to your computer and use it in GitHub Desktop.
Create raincloud plots with ggplot2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
raincloudplot <- function(data, y, fill, x = fill, cols = NULL, | |
boxplots = c("below", "in", "none")) { | |
require(dplyr) | |
require(ggplot2) | |
source("https://raw.githubusercontent.com/datavizpyr/data/master/half_flat_violinplot.R") | |
boxplots <- match.arg(boxplots) | |
p <- ggplot(data, aes_string(y = y, x = x, fill = fill)) + | |
geom_flat_violin(position = position_nudge(x = .2, y = 0), trim = FALSE) | |
p <- p + geom_point(position = position_jitter(width = .15), size = 1, | |
pch = 21, colour = "black") + | |
coord_flip() + | |
theme_classic() + | |
theme(legend.position = "n", panel.grid.major = element_line(), | |
panel.grid.minor = element_line()) | |
if (boxplots == "below") { | |
p <- p + geom_boxplot(width = .1, outlier.shape = NA, alpha = 0.5) | |
} else if (boxplots == "in") { | |
p <- p + geom_boxplot(width = .1, outlier.shape = NA, alpha = 0.5, | |
position = position_nudge(x = 0.2)) | |
} | |
if (is.null(cols)) { | |
n <- length(unique(data[, fill])) | |
p <- p + ggplot2:::manual_scale(c("fill", "colour"), rainbow(n)) | |
} else { | |
p <- p + ggplot2:::manual_scale(c("fill", "colour"), values = cols) | |
} | |
p | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment