Andres Gonzalez
Andres Gonzalez

Reputation: 329

fill areas in geom_point

I have a geom_point graph in which I need to fill the area between points that makes an square. Here is a reproducible example:

#Create variable
square_points <- c ("a1", "a2", "a3", "a4", "b1", "b2", "b3", "b4") #TWO SQUARES:A and B 
x <- c(10, 10, 15, 15, 5, 5, 7,7)
y <- c(20, 25, 20, 25, 10, 15,10,15)
base_squares <- data.frame(square_points, x, y)

#graph: I need to fill the squares with differtent color.
ggplot(base_squares, aes(x = x, y = y))+
  geom_point() +  geom_text(aes(label=square_points))

I need to fill the areas of the points a1, a2, a3 and a4 (same with b points) in different colors. Does anybody knows how can I do this? Thanks in advance!

Upvotes: 0

Views: 54

Answers (1)

canovasjm
canovasjm

Reputation: 513

You can use geom_rect(); see more details here. Using your sample data:

library(ggplot2)

ggplot(base_squares, aes(x = x, y = y)) + 
  geom_rect(aes(xmin = 10, xmax = 15, ymin = 20, ymax = 25, fill = "square1")) +
  geom_rect(aes(xmin = 5, xmax = 7, ymin = 10, ymax = 15, fill = "square2")) +
  geom_text(label = square_points) +
  scale_fill_manual(values = c("red", "lightblue"), 
                    labels = c("square1", "square2"))

enter image description here

If you don't like hardcoding xmin, xmax, ymin and ymax values, then you will need to reshape your data: this tutorial can help you to see how. The downside of this approach is that labeling points (a1, a2, etc.) gets harder.

Upvotes: 1

Related Questions