0

Is there a better way to add all of these segments to a ggplot rather than having each individual line?

  annotate("segment", x = -250, xend = -250, y = -50, yend = 315, colour = "gray50") +
  annotate("segment", x = 250, xend = 250, y = -50, yend = 315, colour = "gray50") +
  annotate("segment", x = -250, xend = 250, y = -50, yend = -50, colour = "gray50") +
  annotate("segment", x = -211, xend = -211, y = -50, yend = 110, colour = "gray50") +
  annotate("segment", x = 211, xend = 211, y = -50, yend = 110, colour = "gray50") +
  annotate("segment", x = -30, xend = 30, y = -10, yend = -10, colour = "gray50") +
  annotate("segment", x = -80, xend = -80, y = -50, yend = 140, colour = "gray50") +
  annotate("segment", x = -60, xend = -60, y = -50, yend = 140, colour = "gray50") +
  annotate("segment", x = 60, xend = 60, y = -50, yend = 140, colour = "gray50") +
  annotate("segment", x = 80, xend = 80, y = -50, yend = 140, colour = "gray50") +
  annotate("segment", x = -80, xend = 80, y = 140, yend = 140, colour = "gray50") +
  annotate("segment", x = 0, xend = 0, y = -10, yend = -5, colour = "gray50")
LBV
  • 123
  • 1
  • 6
  • Your desired coordinates should all be in a dataframe. – Marius Jul 24 '18 at 23:40
  • 1
    Yeah, put your data in vectors and do (for the first three lines) `annotate("segment", x = c(-250, 250, -250), xend = c(-250, 250, 250), y = c(-50, -50, -50), yend = c(315, 315, -50), color = "gray50")`. Or if it's in a data frame just add a `geom_segment(data = your_segment_data, aes(...))` layer. – Gregor Thomas Jul 24 '18 at 23:40

2 Answers2

3

You can give vectors to annotate, e.g., for your first three points (I'm too lazy to type them all)

annotate("segment", x = c(-250, 250, -250),
  xend = c(-250, 250, 250),
  y = c(-50, -50, -50),
  yend = c(315, 315, -50),
  color = "gray50")

Alternately, if your data is in a data frame, use a geom_segment layer (extend to all your points as needed):

annotation_data = data.frame(x1 = c(-250, 250, -250),
      x2 = c(-250, 250, 250),
      y1 = c(-50, -50, -50),
      y2 = c(315, 315, -50))

geom_segment(data = annotation_data,
  mapping = aes(x = x1, xend = x2, y = y1, yend = y2),
  color = "gray50)
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
0

Store your plot in a variable:

library(ggplot2)

data(diamonds)

chart <- ggplot(diamonds, aes(x=depth, y=price)) + 
  geom_point(alpha=0.1)

And store your x, xend, y & yend attributes in something you can loop through like a list:

segment_coords <- list(
  c("x"=250, "xend"=-250, "y"=-50, "yend"=315),
  c("x"=250, "xend"=250, "y"=-50, "yend"=315)
)

Now you can create the segments in a for loop nd add them to your chart like this:

for (segment in segment_coords) {
  chart <- chart + annotate(
    "segment",
    x = segment["x"],
    xend = segment["xend"],
    y = segment["y"],
    yend = segment["yend"],
    colour = "gray50"
  )
}

chart
Eugene Brown
  • 4,032
  • 6
  • 33
  • 47