I'm building a line chart and I'd like the (markdown-formatted) legend labels to be displayed right next to the last data point for each line; something like this:
What I've tried:
First attempt: using geom_text
but there are some issues:
- the label is repeated along each data point
- the label is part of the plot, rather than being a legend (so it won't extend past the panel)
- the text is not formatted
dat <- data.frame(
date = c(1:5, 1:5),
type = rep(c("*Paella* eating", "*Pho* eating"), each = 5),
value = c(15, 28, 36, 49, 47,
25, 35, 31, 24, 24))
library(ggplot2)
dat |>
ggplot(aes(date, value, colour = type)) +
geom_line() +
geom_text(aes(label = type)) +
theme(legend.text = ggtext::element_markdown()) +
gghighlight::gghighlight(type %in% dat$type)
Second strategy: using gghighlight
, however
- unable to format the text with md
- the label is part of the plot, rather than being a legend (so it won't extend past the panel)
- the label partially hides the line
dat |>
ggplot(aes(date, value, colour = type)) +
geom_line() +
gghighlight::gghighlight(type %in% dat$type) +
theme(strip.text = ggtext::element_markdown())
Created on 2022-10-26 with reprex v2.0.2