Created
February 23, 2019 05:15
-
-
Save goldingn/79e797fc61902d0003a9ba5a8436722e to your computer and use it in GitHub Desktop.
a box-esque plot with a greyscale gradient showing the density of data
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
# box-ish plot with colour gradient giving smoothed densities | |
# some fake values | |
x <- c(rnorm(150, -0.5, 1.3), | |
rnorm(30, -1, 0.8), | |
rnorm(20, 0.1, 0.6)) | |
# how smooth the gradient is | |
n_levels <- 100 | |
# kernel density estimate, to smooth out the gradient | |
d <- density(x, n = n_levels, adjust = 2) | |
dens <- d$y / max(d$y) | |
locs <- d$x | |
# boundaries for plotting | |
lower <- locs[-length(locs)] | |
upper <- locs[-1] | |
# shades for plotting | |
levels <- 0.95 - dens / 2 | |
cols <- grey(levels) | |
# assume it's on an empty boxplot | |
plot.new() | |
boxplot(x, lty = 0, cex = 0, ylim = range(d$x) * 1.2, las = 2) | |
# plot all segments of density | |
for (i in seq_len(n_levels)) { | |
rect(0.8, lower[i], | |
1.2, upper[i], | |
col = cols[i], | |
lty = 0) | |
} | |
# a border around the whole thing | |
rect(0.8, min(lower), | |
1.2, max(upper), | |
border = grey(0.8)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment