label geom_line with a label

There are some nice packages to wrap with ggplot2 to label specific points on a plot (ggrepel). However, I am having difficulty if I want to label geom_line.

library(tidyverse)
library(ggrepel)
data("Theoph")

Theoph2 <- Theoph %>% 
  filter(Subject %in% c(2, 9, 10)) %>% 
  mutate_at(vars(Dose), as.character)

ggplot(data = Theoph2, aes(Time, conc, color = Dose, group = Dose)) +
  geom_line(size = 1.2) +
  geom_label_repel(aes(label = Dose), nudge_x = 0.35, size = 4)

I would like to label the line with variable = Dose to happen with one time to emphasize in the plot what the line corresponds to. In this example, however, it shows it all every x point in the data.

Here is one way to label each line. You could also make a special data frame to contain the labeling data and use that as the data argument of geom_label.

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
DF <- data.frame(Time = seq(0,24,2),
                 conc= c(0, 9, 7, 6, 5.5, 5, 4, 3.75, 3.5, 2.75,2.5, 2.25, 2,
                         0, 8, 7.5, 6, 5, 4.75, 4.5, 3.2, 2.75, 2.25, 2.05, 1.5, 1.03,
                         0, 10, 9.5, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.25),
                 Dose = rep(c(3.1, 4.4, 5.5), each = 13))
DF <- mutate(DF, Label = ifelse(Time == 24, Dose, NA),
             Dose = as.character(Dose))
ggplot(data = DF, aes(Time, conc,  group = Dose)) +
  geom_line(aes(color = Dose), size = 1.2) +
  geom_label(aes(label = Label), nudge_x = 0.35, size = 4) 
#> Warning: Removed 36 rows containing missing values (geom_label).

Created on 2020-06-25 by the reprex package (v0.3.0)

2 Likes

An alternative to avoid the warning is to pass a filtered data frame to geom_label()

library(ggplot2)
library(dplyr)

DF <- data.frame(Time = seq(0,24,2),
                 conc= c(0, 9, 7, 6, 5.5, 5, 4, 3.75, 3.5, 2.75,2.5, 2.25, 2,
                         0, 8, 7.5, 6, 5, 4.75, 4.5, 3.2, 2.75, 2.25, 2.05, 1.5, 1.03,
                         0, 10, 9.5, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.25),
                 Dose = rep(c(3.1, 4.4, 5.5), each = 13))

ggplot(data = DF, aes(Time, conc,  group = Dose)) +
    geom_line(aes(color = as.factor(Dose)), size = 1.2) +
    geom_label(aes(label = Dose),
               data = DF %>% filter(Time == max(Time)),
               nudge_x = 0.35,
               size = 4) 

Created on 2020-06-25 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.