rggplot2

Add label to right y axis in R ggplot


I have created a plot using the following code

library(dplyr)
library(ggplot2)

df <- data.frame(
  group_val = c(rep('Class A', 10), rep('Class B', 10)),
  x_val = c(seq(1,10), seq(1,10)),
  y_val = c(3,5,4,6,8,11,10,9,8,12,
            6,2,3,6,8,10,12,14,16,8)
)

goal <- 16


df %>%
  ggplot(aes(x=x_val, y=y_val, group=group_val, color=group_val)) +
  geom_line() +
  theme(legend.position="bottom",
        legend.title = element_blank()) + 
  geom_hline(yintercept = goal,
             linetype="dashed")

enter image description here

I want to add a label to the right on the Y-axis to mark the goal. For example (which I've done using MS Paint): enter image description here

How can I do this? I've seen it done in python but am looking for a method in R.


Solution

  • enter image description hereYou could use a custom annotation:

    library(dplyr)
    library(ggplot2)
    library(grid)
    
    df <- data.frame(
      group_val = c(rep('Class A', 10), rep('Class B', 10)),
      x_val = c(seq(1,10), seq(1,10)),
      y_val = c(3,5,4,6,8,11,10,9,8,12,
                6,2,3,6,8,10,12,14,16,8)
    )
    
    goal <- 16
    
    df %>%
      ggplot(aes(x=x_val, y=y_val, group=group_val, color=group_val)) +
      coord_cartesian(clip = "off") +
      geom_line() +
      scale_x_continuous(limits = range(df$x_val))+
      theme(legend.position="bottom",
            legend.title = element_blank()) + 
      geom_hline(yintercept = goal,
                 linetype="dashed")+
        annotation_custom(
          grob = grid::textGrob(label = "← Goal", hjust = 0, gp = gpar(cex = 0.8)),
          xmin = max(df$x_val)+.75, 
          xmax = max(df$x_val)+.75, 
          ymin = goal, 
          ymax = goal)+
      theme(plot.margin = margin(1,2,1,1, "cm"))