【发布时间】:2012-07-17 18:38:33
【问题描述】:
# data
set.seed (123)
xvar <- c(rnorm (1000, 50, 30), rnorm (1000, 40, 10), rnorm (1000, 70, 10))
yvar <- xvar + rnorm (length (xvar), 0, 20)
myd <- data.frame (xvar, yvar)
# density plot for xvar
upperp = 80 # upper cutoff
lowerp = 30 # lower cutoff
x <- myd$xvar
plot(density(x))
dens <- density(x)
x11 <- min(which(dens$x <= lowerp))
x12 <- max(which(dens$x <= lowerp))
x21 <- min(which(dens$x > upperp))
x22 <- max(which(dens$x > upperp))
with(dens, polygon(x = c(x[c(x11, x11:x12, x12)]),
y = c(0, y[x11:x12], 0), col = "green"))
with(dens, polygon(x = c(x[c(x21, x21:x22, x22)]),
y = c(0, y[x21:x22], 0), col = "red"))
abline(v = c(mean(x)), lwd = 2, lty = 2, col = "red")
# density plot with yvar
upperp = 70 # upper cutoff
lowerp = 30 # lower cutoff
x <- myd$yvar
plot(density(x))
dens <- density(x)
x11 <- min(which(dens$x <= lowerp))
x12 <- max(which(dens$x <= lowerp))
x21 <- min(which(dens$x > upperp))
x22 <- max(which(dens$x > upperp))
with(dens, polygon(x = c(x[c(x11, x11:x12, x12)]),
y = c(0, y[x11:x12], 0), col = "green"))
with(dens, polygon(x = c(x[c(x21, x21:x22, x22)]),
y = c(0, y[x21:x22], 0), col = "red"))
abline(v = c(mean(x)), lwd = 2, lty = 2, col = "red")
我需要绘制两种密度图,我不确定是否有比以下更好的方法:
ggplot(myd,aes(x=xvar,y=yvar))+
stat_density2d(aes(fill=..level..), geom="polygon") +
scale_fill_gradient(low="blue", high="green") + theme_bw()
我想将所有三种类型合二为一(我不知道我是否可以在 ggplot 中创建双向图),对于解决方案是在 ggplot 中还是在基础中还是在混合中没有优先级。考虑到 R 的稳健性,我希望这是一个可行的项目。我个人更喜欢 ggplot2。
注意:此图中的下阴影不正确,xvar 和 yvar 图中的红色应始终位于下方,绿色始终位于上方,对应于 xy 密度图中的阴影区域。
编辑: 对图表的最终期望(感谢 seth 和 jon 非常接近的答案)
(1) 删除空格和轴刻度标签等使其紧凑
(2) 网格对齐,以便中间的绘图刻度和网格应与侧刻度对齐,并且绘图的标签和大小看起来相同。
【问题讨论】:
-
此处的答案可能有助于使用 ggplot stackoverflow.com/questions/8545035/… 获得密度
-
您的问题非常鼓舞人心,我想知道您是否可以分享能够在您的帖子中绘制图形的最终代码?非常感谢。
标签: r graph ggplot2 kernel-density