Home > Mobile >  Labelling points with ggrepel using a second dataframe
Labelling points with ggrepel using a second dataframe

Time:01-09

I have two lines that I wish to label with ggrepel. I require a second, separate dataframe to have the label information.

The error I get is:

Error in `geom_label_repel()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 2nd layer.
Caused by error in `FUN()`:
! object 'comp' not found
Run `rlang::last_error()` to see where the error occurred.

I thought when I assign new data to geom_label_repel(data = comp_label_df the old dataframe, df, would not be referenced. That is why I am puzzled by the error that refers to comp which is a column header in df.

How do I label the two lines at x = "2023-01-08"?

library("tidyverse")
library("ggrepel")

d1 <- as.Date("2023-01-07")
d2 <- as.Date("2023-01-08")
d3 <- as.Date("2023-01-09")

comp_label_df <- tibble(
  x = c(d2, d2),
  one = c(1.3, 2.5),
  label = c("Line 1", "Line 2")
)

df <- tibble(
  comp = c("A", "B", "A", "B", "A", "B"),
  one = c(1, 1.1, 1.3, 2.5, 5, 8),
  date = c(d1, d1, d2, d2, d3, d3)
)

# OK
ggplot(data = df, aes(x = date, y = one, group = comp))  
  geom_line() 

# ERROR
ggplot(data = df, aes(x = date, y = one, group = comp))  
  geom_line()  
  geom_label_repel(data = comp_label_df, aes(x = x, y = one, label = label)) 

  

CodePudding user response:

aesthetics are passed on to lower layers if defined at the parent level. Since comp is not present in comp_label_df it returns an error. Specify aesthetics at geom level.

library(ggplot2)
library(ggrepel)

ggplot(data = df)  
  geom_line(aes(x = date, y = one, group = comp))  
  geom_label_repel(data = comp_label_df, aes(x = x, y = one, label = label))

enter image description here

  • Related