【发布时间】:2015-12-19 18:48:58
【问题描述】:
我的意图是对位于两点之间的密度曲线下方的区域进行阴影处理。在此示例中,我想对值 0.25 和 0.5 之间的区域进行着色。
我已经能够用以下方法绘制我的密度曲线:
setwd("D:/Workspace")
# -- create dataframe
coursename <- c('Math','Math','Math','Math','Math')
value <- c(.12, .4, .5, .8, .9)
df <- data.frame(coursename, value)
library(ggplot2)
density_plot <- ggplot(aes(x=value, colour=coursename, fill=coursename), data=df) +
geom_density(alpha=.3) +
geom_vline(aes(xintercept=.5), colour="blue", data=df, linetype="dashed", size=1) +
scale_x_continuous(breaks=c(0, .25, .5, .75, 1), labels=c("0", ".25", ".5", ".75", "1")) +
coord_cartesian(xlim = c(0.01, 1.01)) +
theme(axis.title.y=element_blank(), axis.text.y=element_blank()) +
ggtitle("sample data")
density_plot
我尝试使用以下代码对 0.25 和 0.5 之间的区域进行着色:
x1 <- min(which(df$value >=.25))
x2 <- max(which(df$value <=.5))
with(density_plot, polygon(x=c(x[c(x1,x1:x2,x2)]), y=c(0, y[x1:x2], 0), col="gray"))
但它只会产生以下错误:
Error in xy.coords(x, y) : object 'y' not found
【问题讨论】:
-
有两件事可以直接回到你的 q 中。 (1) 找不到
y,因为您在对polygon的调用中引用了y[x1:x2](并且没有y); (2) 您正在尝试混合 ggplot2/grid 和基本图形。
标签: r graphics ggplot2 polygon