Arnav Harkenavvy
Arnav Harkenavvy

Reputation: 115

How do I fill the space between multiple line segments in ggplot?

Suppose I have the following plot in ggplot2:

p <- ggplot() +
  geom_point(aes(x=15,y=50),shape=19,fill="gray0", size=5)+
  geom_point(aes(x=28, y=75),shape=19, fill="gray0", size=5)+
  geom_point(aes(x=13, y=100),shape=19, fill="gray0", size=5)+
  geom_segment(aes(x = 15, y = 50, xend = 28, yend = 75), size=1)+
  geom_segment(aes(x = 13, y = 100, xend = 28, yend = 75), size=1)+
  geom_segment(aes(x = 15, y = 50, xend = 13, yend = 100), size=1)

This plots three line segments intersecting at common points so that a triangle is created. How would I then fill the formed triangle with a color? (Suppose I need to use geom_segment)

Upvotes: 0

Views: 642

Answers (1)

jeffverboon
jeffverboon

Reputation: 336

You can use geom_polygon instead:

df <- data.frame(x = c(15, 28, 13), y = c(50,75,100))

ggplot() +
      geom_point(df, mapping = aes(x = x, y = y), size = 5) +
      geom_polygon(df, mapping=aes(x = x, y = y), fill="grey")

you may want the points on top of the triangle and if so do geom_polygon then geom_point

Upvotes: 2

Related Questions