Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill the region between two lines with ggplot2 in R

Tags:

plot

r

ggplot2

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?

like image 939
VLC Avatar asked Oct 15 '13 17:10

VLC


1 Answers

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.

like image 158
joran Avatar answered Oct 21 '22 16:10

joran