使用geom_polygon在ggplot中的非矩形区域着色

时间:2019-02-04 23:54:42

标签: r ggplot2

我在ggplot中为非矩形区域着色时遇到麻烦。我希望能够以与rethinking软件包shade()中的函数相同的方式进行着色,该软件包似乎使用了polygon()函数。您将需要安装rethinking()软件包。这是有关如何使用重新思考软件包中的基础plotshade进行操作的数据和代码。

library(rethinking)
data(Howell1)
d <- Howell1
d2 <- d[d$age >= 18,]
m4.3 <- map(
  alist(height ~ dnorm(mu, sigma),
        mu <- a + b*weight,
        a ~ dnorm(178, 20),
        b ~ dnorm(0, 10),
        sigma ~ dunif(0, 50)),
  data = d2)
weight.seq <- seq(from = 25, to = 70, by  = 1)
mu <- link(m4.3, data = data.frame(weight = weight.seq))
mu.HPDI <- apply(mu, 2, HPDI, prob = 0.95)

# plot raw data
plot(height ~ weight, data = d2, col = col.alpha(rangi2, 0.5))

# plot a shaded region for 95% HPDI
shade(mu.HPDI, weight.seq)

因此可见清晰的阴影区域。

现在这是我在ggplot中使用geom_polygon的尝试,它需要创建一个长数据框以传递多边形的坐标。

HPDIDF <- data.frame(weight.seq = weight.seq,
                     muHPDI_lo = mu.HPDI[1,],
                     muHPDI_hi = mu.HPDI[2,])
hpdiLong <- gather(HPDIDF, key = lowHi, value = predH, muHPDI_lo, muHPDI_hi) 

现在该图

ggplot(d2, aes(weight, height)) +
       geom_point(shape = 1, colour = "blue") + # graph original data
       geom_polygon(data = hpdiLong, aes(weight.seq, predH), fill = "grey") +
       theme_classic()

shade()函数相比,生成的阴影区域确实不令人满意。知道怎么做吗?

0 个答案:

没有答案