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
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
andquantile
from the basestats
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 usinggeom_ribbon
and ggplot's intended aesthetic system; no need to go digging through the plot object.Here is a solution using the function
WVPlots::ShadedDensity
. I will use this function because its arguments are self-explanatory and therefore the plot can be created very easily. On the downside, the customization is a bit tricky. But once you worked your head around aggplot
object, you'll see that it is not that mysterious.Now you can create your plot.
But since you want the colour of the line to be lightblue etc, you need to manipulate the object
p
. In this regard, see also this and this question.The object
p
contains four layers:geom_line
,geom_ribbon
,geom_vline
andgeom_text
. You'll find them here:p$layers
.Now you need to change their aesthetic mappings. For
geom_line
there is only one, thecolour
If you now want to change the line colour to be lightblue simply overwrite the existing colour like so
Once you figured how to do that for one
layer
, the rest is easy.And the plot now looks like this