在ggplot的geom_density()中为每个分位数填充不同的颜色 [英] Fill different colors for each quantile in geom_density() of ggplot

查看:379
本文介绍了在ggplot的geom_density()中为每个分位数填充不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ggplot显示数据的百分位数.我正在使用以下代码,

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")

以下是我得到的图形,

我希望为每个段填充不同的颜色.即0-25%的一种颜色和25-50%的另一种颜色.可以这样做吗?

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?

推荐答案

仅从 Sam指向的位置复制答案

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")

这篇关于在ggplot的geom_density()中为每个分位数填充不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆