Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add label to right y axis in R ggplot

Tags:

r

ggplot2

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.

like image 473
figNewton Avatar asked Dec 08 '25 08:12

figNewton


1 Answers

Besides using an annotation which always requires some fiddling to make room for and to place the annotation another option would be to use the secondary axis trick, i.e. add your annotation via a secondary axis. A small downside is that we need to get rid of the axis ticks using theme options:

library(ggplot2)

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"
  ) +
  scale_y_continuous(
    sec.axis = dup_axis(
      breaks = goal,
      labels = "\u2190 Goal",
      name = NULL
    )
  ) +
  theme(
    axis.text.y.right = element_text(
      size = 12, face = "bold", margin = margin(l = 10)
    ),
    axis.ticks.y.right = element_blank(),
    axis.ticks.length.y.right = unit(0, "pt")
  )

like image 200
stefan Avatar answered Dec 11 '25 06:12

stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!