用R中的ggplot2填充两行之间的区域

时间:2013-10-15 17:20:15

标签: r plot ggplot2

这是一个玩具数据集:

xa <- c(4, 5, 4.5, 4, 3, 1.5)
ya <- c(1, 2, 4, 5, 5.5, 6)
xb <- c(3.8, 4.5, 4, 3.5, 2.5, 1)
yb <- c(1, 2, 3, 4, 5, 5.8)
toyset <- as.data.frame(cbind(xa, ya, xb, yb))

如果我们只绘制连接它们的点和线,我们得到:

library(ggplot2)
ggplot(toyset) + geom_path(aes(xa, ya)) + geom_path(aes(xb, yb)) +
  geom_point(aes(xa, ya)) + geom_point(aes(xb, yb))

enter image description here

ggplot2 中是否有一种简单的方法可以填充由两条线定义的区域?

1 个答案:

答案 0 :(得分:5)

您可以使用geom_polygon

poly_df <- rbind(setNames(toyset[,1:2],c('x','y')),
                 setNames(toyset[6:1,3:4],c('x','y')))

ggplot(toyset) + 
    geom_path(aes(xa, ya)) + 
    geom_path(aes(xb, yb)) +
    geom_point(aes(xa, ya)) + 
    geom_point(aes(xb, yb)) +
    geom_polygon(data = poly_df,aes(x = x,y = y),fill = "lightblue",alpha = 0.25)

我修复了样本数据中的拼写错误(54)。请注意,您必须非常小心多边形数据框中点的顺序。这与geom_path的交易相同。