5

这是一个玩具数据集:

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))

在此处输入图像描述

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

4

1 回答 1

6

您可以使用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

于 2013-10-15T18:21:08.050 回答