0

I have the following graph.

ggplot() +
  geom_hline(aes(yintercept = 0, linetype = "Line 1"), color = "white", size = 1.25) +
  geom_hline(aes(yintercept = 0, linetype = "Line 2"), color = "white", size = 1.25) +
  scale_linetype_manual(name = "Reference Lines", values = rep("dashed", 2), guide = guide_legend(override.aes = list(color = c("red", "green")))) +
  theme_void()

Graph

How can I center the legend in the plot area? I made the actual graph completely white because I'm just interested in the legend in this case.

1
  • 1
    Try adding theme(legend.position = "inside", legend.position.inside = c(0.5, 0.5)) to your code? I'm assuming by "center", you would like the legend to be both vertically and horizontally centered inside the plot area. Commented May 21 at 21:53

1 Answer 1

1

With version 3.5.0 of {ggplot2} and later, you can use arguments legend.position amd legend.position.inside in the theme() function to set co-ordinates on a [0,1] grid specifying where you want the legend to be:

ggplot() +
  geom_hline(aes(yintercept = 0, linetype = "Line 1"), color = "white", size = 1.25) +
  geom_hline(aes(yintercept = 0, linetype = "Line 2"), color = "white", size = 1.25) +
  scale_linetype_manual(
    name = "Reference Lines",
    values = rep("dashed", 2),
    guide = guide_legend(override.aes = list(color = c("red", "green")))
  ) +
  theme_void() +
  theme(legend.position = "inside",
        legend.position.inside = c(0.5, 0.5))

enter image description here

With older versions, theme(legend.position = c(0.5, 0.5)) should work.

Not the answer you're looking for? Browse other questions tagged or ask your own question.