Skip to content

Instantly share code, notes, and snippets.

@Rekyt
Created January 13, 2016 10:59
Show Gist options
  • Select an option

  • Save Rekyt/f2b7f07a066c0203eb42 to your computer and use it in GitHub Desktop.

Select an option

Save Rekyt/f2b7f07a066c0203eb42 to your computer and use it in GitHub Desktop.
plot of density of a given vector of numbers with quantile areas colored
# Script to make a plot of density of a given vector of numbers with quantile
# areas colored
# Package -------------------------------------------------------------------
library(ggplot2)
library(dplyr)
# Function ------------------------------------------------------------------
make_quantile_density = function(ex_vector, probs = NULL) {
# Get rid of 'NA'
ex_vector = na.omit(ex_vector)
# Compute deciles by default if not quantiles provided
if (is.null(probs)) {
quant = quantile(ex_vector, probs = seq(0, 1, 0.1))
} else {
quant = quantile(ex_vector, probs = probs)
}
# Compute density and select data in dataset
dens_df = with(density(ex_vector), data.frame(x, y)) %>%
filter(x >= quant[[1]], x <= quant[[length(quant)]])
# Add quantile number for all dataset
dens_df$quant = cut(dens_df$x, breaks = quant)
# Make nice labels for legend
qname = names(quant)
qlabels = paste(qname[-length(qname)], qname[-1], sep = "-")
# Plot
p_dens_col = ggplot(dens_df, aes(x = x, y = y)) +
geom_area(aes(fill = quant)) +
geom_line() +
# Color palette can be adapted
scale_fill_brewer(palette = "PuOr", labels = qlabels)
return(p_dens_col)
}
# Example -------------------------------------------------------------
ex = rnorm(1000)
p_dens = make_quantile_density(ex)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment