eal*_*ns1 2 graphics r polygon ggplot2
我的目的是遮蔽密度曲线下面两个点之间的区域.在这个例子中,我想遮蔽值.25和.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
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下代码来遮蔽.25和.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"))
Run Code Online (Sandbox Code Playgroud)
但它只会生成以下错误:
Error in xy.coords(x, y) : object 'y' not found
Run Code Online (Sandbox Code Playgroud)
或者使用ggplot2来对抗自己!
coursename <- c('Math','Math','Math','Math','Math')
value <- c(.12, .4, .5, .8, .9)
df <- data.frame(coursename, value)
library(ggplot2)
ggplot() +
geom_density(data=df,
aes(x=value, colour=coursename, fill=coursename),
alpha=.3) +
geom_vline(data=df,
aes(xintercept=.5),
colour="blue", 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
density_plot
dpb <- ggplot_build(density_plot)
x1 <- min(which(dpb$data[[1]]$x >=.25))
x2 <- max(which(dpb$data[[1]]$x <=.5))
density_plot +
geom_area(data=data.frame(x=dpb$data[[1]]$x[x1:x2],
y=dpb$data[[1]]$y[x1:x2]),
aes(x=x, y=y), fill="grey")
Run Code Online (Sandbox Code Playgroud)
(这与jlhoward的答案几乎完全相同,但是从ggplot中获取计算值).
| 归档时间: |
|
| 查看次数: |
1805 次 |
| 最近记录: |