I want to add background colour to the different quantiles in a plot. Below I have the start. But not sure how to:
- Keep the values of the x-axes (i.e., now it is the percentages, but I want the scores)
- Control the colours
- 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)
CodePudding user response:
Maybe this is what you are looking for:
- Use
unname(quantiles)
for thebreaks
. Additionally I made use ofscales::number
for nice labels. - You could set your desired colors via
scale_fill_manual
, where personally I prefer using a named vector to assign colors to categories - You could set the transparency via the
alpha
argument ingeom_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)