Create a polygon within a graph in ggplot (R)

Viewed 1751

I am trying to create a polygon on one of my graphs I create in ggplot2 in order to denote a "compositional field". I understand that I should be using the geom_polygon function, but I was unable to successfully input this function. The code I have for my graph is below (less geom_polyon). I included a photo of what I am trying to do on my graph. Essentially, I want to create a polyogon between (x = 8, y = 0.8) and (x = 100, y = 2). Any help is greatly appreciate, thank you.

Image [1]: https://i.stack.imgur.com/MR8pj.png

Graph script

ggplot(data = ZonesPd, aes(x = Pd_ppm, y = Cu.Pd)) +

geom_point(aes(color = Mineralized.Zone, size = Mineralized.Zone), alpha = 0.5) +

scale_x_log10(limit = c(1e-3, 1e3), expand = c(0, 0)) +
  scale_y_log10(limit = c(1e2, 1e5), expand = c(0, 0)) +

scale_size_manual(values = c(0.5, 0.5, 3)) +

theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.ticks.length = unit(-0.24, "cm"),
        axis.text.x = element_text(size = 15, color = "black", margin = margin(0.5, 0.5, 0.5, 0.5, 
          "cm")),
        axis.text.y = element_text(size = 15, color = "black", margin = margin(0.5, 0.5, 0.5, 0.5, 
          "cm")),
        axis.title = element_text(size = 15),
        aspect.ratio = 0.75,
        legend.position = c(0.8, 0.15),
        legend.text = element_text(size = 15),
        legend.title = element_blank())
2 Answers

As suggested by r2evans in the comments, geom_rect is the way to go here:

library(ggplot2)

ZonesPd <- data.frame(Pd_ppm <- 10^rnorm(100), Cu.Pd <- 10^rnorm(100), 
                      Mineralized.Zone=sample(gl(5,20)))

ggplot() +
  geom_point(data = ZonesPd, aes(x = Pd_ppm, y = Cu.Pd, color = Mineralized.Zone, size = Mineralized.Zone), alpha = 0.5) +
  scale_x_log10() + scale_y_log10() +
  geom_rect(aes(xmin=8, xmax=100, ymin=0.8, ymax=8))

example output

If you are happy with your plot and just want to add a rectangle with corners at (x = 8, y = 0.8) and (x = 100, y = 2), try adding:

+ geom_polygon(data = data.frame(x = c(8, 8, 100, 100), y = c(.8, 2, 2, .8)),
               aes(x = x, y = y, alpha = 0.5))
Related