我想為圖中的不同分位數添加背景顏色。下面我開始了。但不確定如何:
- 保留 x 軸的值(即,現在是百分比,但我想要分數)
- 控制顏色
- 設定顏色的透明度
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)

uj5u.com熱心網友回復:
也許這就是你要找的:
- 使用
unname(quantiles)了breaks。此外,我使用scales::number了漂亮的標簽。 - 您可以通過 設定您想要的顏色
scale_fill_manual,我個人更喜歡使用命名向量為類別分配顏色 - 您可以通過
alpha引數設定透明度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)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/319258.html
上一篇:在R中繪制回歸串列的系數
下一篇:使用ggplot2繪制雙向條形圖
