Last active
August 30, 2017 04:00
-
-
Save Rekyt/f2ee61aa39c8b7684965 to your computer and use it in GitHub Desktop.
Color Quantile from a density in ggplot2 with labeled quantiles
This file contains hidden or 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
# Script from a density to color quantiles area | |
# Packages --------------------------------------------------------------------- | |
library(ggplot2) | |
library(dplyr) | |
# Data ------------------------------------------------------------------------- | |
r_data = rnorm(100) # Computes 100 values | |
r_quant = quantile(r_data, probs = seq(0, 1, 0.1)) # Computes quantiles | |
# Make a df with column x & y extracted from density object | |
dens = with(density(r_data), data.frame(x, y)) %>% | |
filter(x >= r_quant[1], x <= r_quant[length(r_quant)]) | |
# Add columns to classify by quantile | |
dens$quant = cut(dens$x, breaks = r_quant) | |
# Get names of quantiles (i.e. '10%', etc.) | |
q_names = names(r_quant) | |
# Make a vector of potential labels of quantiles (i.e. '0%-10%' | |
q_labels = paste(q_names[-length(q_names)], q_names[-1], sep = "-") | |
# Plot ------------------------------------------------------------------------- | |
# Basic Plot | |
p_dens = ggplot(dens, aes(x = x, y = y)) + | |
geom_area(aes(fill = quant)) + | |
geom_line(size = 2) | |
# Plot with diverging color scale around 50% quantile | |
p_dens + scale_fill_brewer(palette = "PuOr") | |
# Plot with diverging color scale and nicely labeled quantiles | |
p_dens + scale_fill_brewer(palette = "PuOr", labels = q_labels) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment