VLC
VLC

Reputation: 1179

Fill the region between two lines with ggplot2 in R

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

enter image description here

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

Upvotes: 6

Views: 4427

Answers (1)

joran
joran

Reputation: 173517

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.

Upvotes: 7

Related Questions