1

I want to apply geom label only to the last value data point of each serie. This is my database:

This is my code:

paises <- c("Peru", "Brazil", "Colombia", "Ecuador", "Chile", "Argentina", "Uruguay", "Paraguay", "Bolivia")

data <- jhu_sitrep_import(source = "confirmed") %>%
  jhu_sitrep_cleandb() %>%
  filter(country_region %in% paises) %>%
  filter(value>0) %>%
  group_by(country_region) %>%
  mutate(start = first(dates),
         d_start = dates-start,
         per = ifelse(country_region =="Peru","Per","Otros"),
         max_cases = max(value)) %>%
  filter(max_cases>30)

data %>%
  filter(per =="Otros") %>%
  ggplot(aes(x = d_start, y = value, group=country_region)) +
  geom_line(aes(col = country_region)) +
  geom_point(aes(col = country_region, shape = country_region)) +
  geom_line(dat = data %>% filter(per=="Per"), col = "red") +
  geom_label(aes(y = value, label =value), vjust = 0.5) +
  geom_label(aes(y = value, label =value ), vjust = -0.5) +
  geom_point(dat = data %>% filter(per=="Per"), col = "red") +
  geom_text(data = data %>% slice(n()) %>% filter(country_region!="Peru"),
            aes(y = value, label = country_region, col = country_region), vjust=-.5) +
  geom_text(data = data %>% slice(n()) %>% filter(country_region=="Peru"),
            aes(y = value, label = country_region), col = "red", vjust=-.5) +
  scale_fill_discrete_qualitative(palette="Pastel 1", nmax = 14, order = 5:14) +
  labs(color = "Paises", x = "Días desde primer caso", y = "Numero de casos", shape = "Paises") +
  scale_y_log10() + 
  theme(legend.position = "bottom")

So with my code I get the value for each value data point. I just want the label for the last value.

This my plotenter image description here

2 Answers 2

6

You'd want to filter/subset your data just to the last point, and pass that into the geom_label() using the data argument.

I've included a reprex (reproducible example) below.

library(tidyverse)

cars <- rownames_to_column(mtcars, var = "model")

ggplot(cars, aes(x = mpg, y = disp)) +
  geom_point() +
  geom_label(data = filter(cars, model == last(model)), aes(label = model))

Created on 2020-03-20 by the reprex package (v0.3.0)

2

You could also create a new label column using ifelse storing the value only for the last value and the rest as NAs. And then use this column as the label aesthetic in geom_label

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.