How can I put labels of the legend at the end of each line in ggplot?
The two labels of the legends overlap.
geom_text
hasn't got the right group
parameter probably.
df <- structure(list(Epreuve = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), levels = "CE", class = "factor"), Country = structure(c(1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L), levels = c("Country1", "Country2"), class = "factor"), Month = structure(c(18779, 18779, 18809, 18809, 18840, 18871, 18871, 18901, 18901, 18932, 18962, 18962, 18993, 19024, 19024, 19052, 19083, 19113, 19144, 19144), class = "Date"), moyenn_gliss = c(55, 62, 47.5, 68.5, 44.6666666666667, 36, 45.6666666666667, 38, 25, 41.6666666666667, 48.6666666666667, 16.6666666666667, 52, 45.6666666666667, 25, 34, 23.3333333333333, 17.6666666666667, 25.3333333333333, 51.6666666666667), nb_total = c(250L, 38L, 250L, 38L, 250L, 250L, 38L, 250L, 38L, 250L, 250L, 38L, 250L, 250L, 38L, 250L, 250L, 250L, 250L, 38L), grp = c(4L, 3L, 4L, 3L, 4L, 4L, 3L, 4L, 3L, 4L, 4L, 3L, 4L, 4L, 3L, 4L, 4L, 4L, 4L, 3L)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"))
p <- df %>%
ggplot(aes(Month, moyenn_gliss, color = interaction(Country, Epreuve, drop = T, sep = " ")))
geom_point(aes(size = size_pt <<- grp)) geom_line(aes(size = size_pt * 0.7))
# The following geom_text does not produce the desired output
geom_text(aes(x = last(unique(Month)), y = last(moyenn_gliss), label = paste(Country, Epreuve), color = interaction(Country, Epreuve, drop = T, sep = " ")))
scale_x_date(breaks = unique(df$Month), date_labels="%b %y")
ggplotly(p)
CodePudding user response:
You can add a column "label" which has the label for each group at the latest date like this:
library(ggplot2)
library(plotly)
library(dplyr)
p <- df %>%
mutate(label = ifelse(Month == max(Month), paste(Country, Epreuve), NA)) %>%
ggplot(aes(Month, moyenn_gliss, color = interaction(Country, Epreuve, drop = T, sep = " ")))
geom_point(aes(size = size_pt <<- grp))
geom_line(aes(size = size_pt * 0.7))
geom_text(aes(label = label, y = moyenn_gliss 2), size = 3)
scale_x_date(breaks = unique(df$Month), date_labels="%b %y")
ggplotly(p)
Output: