Home > Enterprise >  Add colours to the quantiles using ggplot
Add colours to the quantiles using ggplot

Time:10-16

I want to add background colour to the different quantiles in a plot. Below I have the start. But not sure how to:

  1. Keep the values of the x-axes (i.e., now it is the percentages, but I want the scores)
  2. Control the colours
  3. Set the transparency of the colour
dt <- data.frame(scores=rnorm(200))
dens <- density(dt$scores)
df <- data.frame(x=dens$x, y=dens$y)

quantiles <- quantile(dt$scores, prob=c(0.25, 0.5, 0.75))
df$quantile <- factor(findInterval(df$x, quantiles))
levels(df$quantile) <- c("<25%", "25%-50%", "50-75%", "75-100%")

ggplot(df, aes(x, y))   
  geom_line()   
  geom_ribbon(aes(ymin=0, ymax=y, fill=quantile))   
  scale_x_continuous(breaks=quantiles) 

enter image description here

CodePudding user response:

Maybe this is what you are looking for:

  1. Use unname(quantiles) for the breaks. Additionally I made use of scales::number for nice labels.
  2. You could set your desired colors via scale_fill_manual, where personally I prefer using a named vector to assign colors to categories
  3. You could set the transparency via the alpha argument in geom_ribbon
cols <- c("red", "green", "blue", "purple")
names(cols) <- levels(df$quantile)

library(ggplot2)

ggplot(df, aes(x, y))   
  geom_line()   
  geom_ribbon(aes(ymin=0, ymax=y, fill=quantile), alpha = .2)   
  scale_x_continuous(breaks = unname(quantiles), labels = scales::number)  
  scale_fill_manual(values = cols)

  • Related