Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shaded area under density curve in ggplot2

I have plotted a distribution and I want to shade the area>95 percentile. However when I try to use the different techniques documented here:ggplot2 shade area under density curve by group It does not work as the length of my dataset differ.

AGG[,1]=seq(1:1000)
AGG[,2]=rnorm(1000,mean=150,sd=10)
Z<-data.frame(AGG) 
library(ggplot2)
ggplot(Z,aes(x=Z[,2]))+stat_density(geom="line",colour="lightblue",size=1.1)+xlim(0,350)+ylim(0,0.05)+geom_vline(xintercept=quantile(Z[,2],prob=0.95),colour="red")+geom_text(aes(x=quantile(Z[,2],prob=0.95)),label="VaR 95%",y=0.0225, colour="red")
#I want to add a shaded area right of the VaR in this chart
like image 541
Sabotar Avatar asked Mar 07 '23 04:03

Sabotar


1 Answers

This is a case where ggplot's helper functions and built-in summaries can end up being more troublesome than helpful. In your situation, it's probably best to calculate your summary statistics directly, and then plot those. In the example below, I use density and quantile from the base stats library to compute what will be plotted. Feeding this to ggplot directly ends up being much simpler than trying to manipulate ggplot's summary functions. This way, shading is accomplished using geom_ribbon and ggplot's intended aesthetic system; no need to go digging through the plot object.

rm(list = ls())
library(magrittr)
library(ggplot2)

y <- rnorm(1000, 150, 10)

cutoff <- quantile(y, probs = 0.95)

hist.y <- density(y, from = 100, to = 200) %$% 
  data.frame(x = x, y = y) %>% 
  mutate(area = x >= cutoff)

the.plot <- ggplot(data = hist.y, aes(x = x, ymin = 0, ymax = y, fill = area)) +
  geom_ribbon() +
  geom_line(aes(y = y)) +
  geom_vline(xintercept = cutoff, color = 'red') +
  annotate(geom = 'text', x = cutoff, y = 0.025, color = 'red', label = 'VaR 95%', hjust = -0.1)
print(the.plot)

enter image description here

like image 54
jdobres Avatar answered Mar 19 '23 06:03

jdobres