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")

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):

How can I do this? I've seen it done in python but am looking for a method in R.
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")
)

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