Fill the region between two lines with ggplot2 in

2020-07-14 09:51发布

问题:

This is a toy dataset:

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

If we simply plot the points and lines connecting them we get:

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

Is there a simple way in ggplot2 to fill the region defined by the two lines?

回答1:

You can use 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)

I fixed the typo in your sample data (54). Note that you have to be very careful about the ordering of the points in the data frame for the polygon. It's the same deal as with geom_path.



标签: r plot ggplot2