Reputation: 551
Similar to this question how to add a text label in the y-axis in ggplot2, which lacks an example and a satisfying answer, I wonder wether there is any way to put additional labels on an axis, most of the time this will probably be the y-axis. The additional label should appear at a specified position. It should be possible to style the additonal label independently from the "normal" tick labels. And: it should lack a tick (whereas the "normal" tick labels may/should have ticks).
An example:
# Sample dataframe
df <- data.frame(
x = c(1, 2.6, 3, 4, 5),
y = c(2, 5, 3.6, 8.2, 10),
y_ticks = c(2, 4, 5, 8, 10),
y_labels = c("Low", "Mid-Low", "Medium", "Mid-High", "High")
)
# Create a scatter plot with custom y-axis ticks and labels
library (ggplot2)
ggplot(df, aes(x, y)) +
geom_point() +
scale_y_continuous(breaks = df$y_ticks, labels = df$y_labels)
Which gives:
What I want is to add a label (lets say "lower values") without tickmark at y = 6. I tried to draw it in by hand in red to demonstrate the purpose:
I already tried different things, but I cannot figure this out. Perhaps someone can help?
Upvotes: 0
Views: 767
Reputation: 7979
You could try
df <- data.frame(
x = c(6, 2.6, 3, 4, 5),
y = c(2, 5, 3.6, 8.2, 10),
y_ticks = c(2, 4, 5, 8, 10),
y_labels = c("Low", "Mid-Low", "Medium", "Mid-High", "High")
)
# Create a scatter plot with custom y-axis ticks and labels
library (ggplot2)
ggplot(df, aes(x, y)) +
geom_point() +
scale_y_continuous(breaks = df$y_ticks, labels = df$y_labels) +
annotate("text", y = 6L, x = -Inf, label = "lower", col = "red", hjust = 1.2) +
coord_cartesian(xlim = c(min(df$x), max(df$x)), clip = "off")
Created on 2023-11-29 with reprex v2.0.2
Here we use annotate()
+ coord_cartesian()
with clip = off
to allow displaying text outside the plot. We need to set the xlim
in coord_cartesian
for this. I found the x-position in annotate()
by trial and error. There are certainly more sophisticated approaches.
Edit: As per @teunbrand's suggestion in a comment below, to automatically find a satisfactory x-position do: x = -Inf
to set the label at the leftmost position with hjust = 1
(or larger) to have it right-justified.
Upvotes: 1