2

Suppose I drew the following plot using the code below:

plot

data = data.frame(x = 1:5, y = 1:5)
ggplot(data, aes(x = x, y = y)) + 
  geom_point() +
  geom_text(x = 5, y = 5, label = "aaaaaaaaaaaaaaa", hjust = 0) +
  theme_classic() + 
  theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
  coord_cartesian(clip = "off")

To keep the "aaaaaaaaaaa" inside the plot, I can manually change the plot margin, replacing the "c(1, 1, 1, 1)" with "c(1, 3, 1, 1)."

But is there a way to set margins automatically so that the "aaaaaaaaa" will be within the plot?

For example, if "aaaaaaaa..." were instead 100 characters long, I'd have to change margins again. I'm wondering if there is some way to write the code / use a package such that the plot margins will automatically adjust to always include all geom_text objects.

johnny
  • 571
  • 4
  • 14

1 Answers1

0

This question seems to be answered already, where ggplot2 has added new options for vjust and hjust. You can simply use "inward" to ensure your text does not get clipped:

data = data.frame(x = 1:5, y = 1:5)
ggplot(data, aes(x = x, y = y)) + 
  geom_point() +
  geom_text(x = 5, y = 5, label = "aaaaaaaaaaaaaaa", hjust = 0) +
  theme_classic() + 
  theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
  coord_cartesian(clip = "off")

enter image description here

chemdork123
  • 12,369
  • 2
  • 16
  • 32
  • 6
    It looks like "inward" argument does move the label inside the plot. But would there be a way to we keep the label on the right side of the dot and let the margins adjust automatically? Thank you for this answer though! – johnny Apr 01 '20 at 20:29