0

I am trying to annotate my ggplot figure with some text but I struggle to find an optimal solution. I want to create a margin to the right of the figure so that I can write Course A, Course B and Course C. Now I don't have enough space. I have tried to use plot.margin = unit(c(1,4,1 ,1), "cm") but that doesn't seem to give me space that I can use to annotate the plot. Is there a function in ggplot that I can use?

enter image description here

trainingplot <- ggplot(aggreg.data, aes(x = trainingblock, y = performance)) +
  scale_y_continuous(name = "Time substracted from straight gliding time (sec.)", breaks = seq(-2, 6, 1)) +
  scale_x_discrete() +
  theme_pubr()+
  theme(legend.position="none",
       axis.title.x=element_blank(),
       plot.margin = unit(c(1,4,1 ,1), "cm")) +
  geom_hline(aes(yintercept = 0), linetype = "dashed", size=0.2) +
  annotate("text", x = 5.4, y = -0.4, label = "Course A", size=4) + 
  annotate("text", x = 5.4, y = 0.5, label = "Course B", size=4) +
  annotate("text", x = 5.4, y = 2, label = "Course C", size=4) 
  

Cmagelssen
  • 620
  • 5
  • 21
  • 3
    Try with `+ coord_cartesian(clip = "off")`. Another option would be to increase the expansion of the scale using e.g. `scale_x_discrete(expand = expansion(add = c(.6, 1.2)`, where `.6` is the default expansion applied to a discrete scale. – stefan Sep 30 '21 at 16:46
  • Thanks. That worked. What is 1.2 referring to? – Cmagelssen Sep 30 '21 at 16:56
  • 1
    By default ggplot2 expands a discrete scale by `.6` units on both sides where a unit of `1` is the distance between two categories. Hence `1.2` is simply two times the default expansion, i.e. with `c(.6, 1.2)` we keep the default expansion on the left but double it on the right. – stefan Sep 30 '21 at 17:00
  • Thanks. Extremely valuable information. – Cmagelssen Sep 30 '21 at 17:04

1 Answers1

2

For continuous scales, you can use a secondary axis to annotate particular points in the margin. Example with standard dataset below:

library(ggplot2)

ggplot(economics, aes(date)) +
  geom_line(aes(y = unemploy)) +
  scale_y_continuous(
    sec.axis = dup_axis(
      breaks = tail(economics$unemploy, 1),
      labels = "Unemployment", name = NULL
    )
  ) +
  theme(axis.ticks.y.right = element_blank())

Created on 2021-09-30 by the reprex package (v2.0.1)

teunbrand
  • 33,645
  • 4
  • 37
  • 63