我有一些数据dt = data.table(x=c(1:200),y=rnorm(200))
,我首先使用ggplot2
创建密度图:
plot = ggplot(dt,aes(y)) + geom_density(aes(y=..density..))
有没有办法可以添加类似于this的百分位线?
如果我可以进一步遮蔽图形的片段(由百分位线创建),类似于this,那就太棒了!
答案 0 :(得分:12)
这种可能性受到this answer的极大启发:
dt <- data.table(x=c(1:200),y=rnorm(200))
dens <- density(dt$y)
df <- data.frame(x=dens$x, y=dens$y)
probs <- c(0.1, 0.25, 0.5, 0.75, 0.9)
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")
答案 1 :(得分:5)
myd = data.frame(xvar=rnorm(2000),yvar=rnorm(2000))
xd <- data.frame(density(myd$xvar)[c("x", "y")])
p <- ggplot(xd, aes(x, y)) +
geom_area(data = subset(xd, x < -1), fill = "pink") +
geom_area(data = subset(xd, x < -1.96), fill = "red") +
geom_area(data = subset(xd, x > 1), fill = "lightgreen") +
geom_area(data = subset(xd, x > 1.96), fill = "green") +
geom_line()
p