Display data label in line chart in ggplot2

Asked

Viewed 168 times

2

I have a line chart and I would like to put the label of the state corresponding to the line, but the label is coming out on each data available and not only the last one:

inserir a descrição da imagem aqui

Code I’m working on:

library(tidyverse)

dados <- read_delim("~/Downloads/arquivo_geral.csv", 
                    ";", escape_double = FALSE, trim_ws = TRUE)
dados <- dados[,-1]

dados %>%
  filter(casosAcumulados > 9) %>%
  ggplot(aes(x = data, y = log(casosAcumulados), col = estado)) +
  geom_line() +
  geom_text(aes(label = estado), 
            vjust = -1) +
  theme(legend.box = "none") +
  ggtitle("Casos confirmados - Brasil", "(Em log)")

Database: https://covid.saude.gov.br/

  • Look, just because I didn’t understand the doubt right. You want to put the label on the last spot available on each line?

  • Yes, and that point representing the state.

  • Do all points end on the same date? If yes I think to put geom_text(aes(label = estado, x = ultima_data_da_sua_tabela), &#xA; vjust = -1)

  • If the dates are different you can either vector the dates or change the data of the text geom_text (date = . %>% group_by(status) %>% filter(date== max(date)), aes(label = status), vjust = -1)

  • 2

    I would only change the quantity log (which means less) by a logarithmic scale meu_grafico + scale_y_log10()

1 answer

3


inserir a descrição da imagem aquiOne option is you create an object with state positions on the last day of your data:

nm_estados <- dados %>% 
   filter(data == max(data))

And then use this object in plotting as the source of the names:

dados %>%
   filter(casosAcumulados > 9) %>%
   ggplot(aes(x = data, y = log(casosAcumulados), col = estado)) +
   geom_line() +
   geom_text(aes(label = estado), check_overlap = T, data = nm_estados,
             vjust = -1) +
   theme(legend.box = "none") +
   ggtitle("Casos confirmados - Brasil", "(Em log)")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.