rggplot2graph

ggpplot2 join all points in a graph with a line


Just working on some small data with transformations, and trying to join all the points in the data to create a triangle. I have been successful in some regard, but can't seem to figure out the last bit.

Below is the data I am working with:

library(ggplot2)

x <- c(0, 1, 0)
y <- c(0, 0, 1)
x2 <- c(0, 1, 0) + 1/2
y2 <- c(0, 0, 1) + 1/3

df = data.frame(x, y, x2, y2); df

g = ggplot(data = df, aes(x = x, y = y)) + 
    geom_line() + geom_path()
g
g = g + geom_line(aes(x=x2, y=y2), color = "red") + 
    geom_path() 
g

I would like to have the red lines be joined like the black linesenter image description here


Solution

  • You can use geom_polygon which automatically connects the starting and the end point:

    library(ggplot2)
    
    ggplot(data = df, aes(x = x, y = y)) +
      geom_polygon(
        fill = NA, color = "black"
      ) +
      geom_polygon(aes(x = x2, y = y2),
        fill = NA,
        color = "red"
      )