12

I am using ggplot to show percentiles of the data. I am using the following code,

data <- seq(from=0,to=30,length.out=1000)

q <- quantile(data)

ggplot()+ 
  geom_density(aes(x=data)) +  
  annotate(geom="text", x=q, y=0, label=names(q)) +
  theme(text = element_text(size=10)) +
  geom_vline(x=q, linetype = "longdash")

The following is the graph I am getting,

enter image description here

I am looking to fill different colors for each segment. i.e. for 0-25% one color and 25-50 another color. Is it possible to do that?

Also the vertical lines are running through the entire graph. I want to stop it until the curve alone. Instead of running through it completely.

can anybody help me in doing these both?

Observer
  • 641
  • 2
  • 14
  • 31
  • 2
    It's more likely that we will be able to help you if you make a real reproducible example, i.e. an example with data, to go along with your question. Something we can work from and use to show you how it might be possible to solve your problem. You can have a look at [this SO post](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on how to make a great reproducible example in R. I suspect [a solution](http://docs.ggplot2.org/current/geom_polygon.html) can be made with `geom_polygon()` – Eric Fail Dec 01 '15 at 20:53
  • @EricFail Apologies for not producing the reproducible example. I have updated a sample of it. Is this fine? – Observer Dec 01 '15 at 20:59
  • @EricFail i have already used geom_density for the plot. Can I also use geom_polygon ? – Observer Dec 01 '15 at 21:03
  • 8
    See answers to this question [here](http://stackoverflow.com/questions/14863744/adding-percentile-lines-to-a-density-plot) and [here](http://stackoverflow.com/questions/3494593/shading-a-kernel-density-plot-between-two-points) – Sam Dickson Dec 01 '15 at 21:40

1 Answers1

25

Simply copying answer from where Sam is pointing to

enter image description here

dt <- data.frame(x=c(1:200),y=rnorm(200))
dens <- density(dt$y)
df <- data.frame(x=dens$x, y=dens$y)
probs <- c(0, 0.25, 0.5, 0.75, 1)
quantiles <- quantile(dt$y, prob=probs)
df$quant <- factor(findInterval(df$x,quantiles))
ggplot(df, aes(x,y)) + geom_line() + geom_ribbon(aes(ymin=0, ymax=y, fill=quant)) + scale_x_continuous(breaks=quantiles) + scale_fill_brewer(guide="none")
Community
  • 1
  • 1
Eric Fail
  • 8,191
  • 8
  • 72
  • 128