Skip to content

Instantly share code, notes, and snippets.

@mcanouil
Last active February 2, 2024 23:33
Show Gist options
  • Save mcanouil/e3a56a095684a3d7cf98397cdb50143d to your computer and use it in GitHub Desktop.
Save mcanouil/e3a56a095684a3d7cf98397cdb50143d to your computer and use it in GitHub Desktop.
Density curve splitted by quantiles
# # MIT License
#
# Copyright (c) 2024 Mickaël Canouil
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
library(tidyverse)
x <- abs(rnorm(n = 200, mean = 5, sd = 1) + rexp(n = 200, rate = 0.5))
dta <- as_tibble(density(x)[c("x", "y")])
quanti <- quantile(x, prob = c(0, 0.05, 0.25, 0.5, 0.75, 0.95, 1))
dta <- mutate(.data = dta, quantiles = as.factor(findInterval(x = x, vec = quanti)))
ggplot(data = dta, mapping = aes(x = x, y = y)) +
geom_line(mapping = aes(colour = quantiles)) +
geom_ribbon(mapping = aes(ymin = 0, ymax = y, fill = quantiles, colour = quantiles)) +
geom_vline(xintercept = quanti, linetype = 2) +
scale_x_continuous(breaks = quanti, limits = range(quanti)) +
scale_fill_viridis_d(guide = "none") +
scale_colour_viridis_d(guide = "none")
@mcanouil
Copy link
Author

mcanouil commented Feb 11, 2019

devtools::source_gist("https://gist.github.com/mcanouil/e3a56a095684a3d7cf98397cdb50143d", echo = TRUE)
#> Sourcing https://gist.githubusercontent.com/mcanouil/e3a56a095684a3d7cf98397cdb50143d/raw/aa96bd8ad51a928467ad3c94b70846dcea3cf0dc/density.r
#> SHA-1 hash of file is 8214de70323f9fcb1aae7cd6f391bcb9a6bc0cf2
#> Warning: Removed 80 rows containing missing values (geom_path).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment