Sort legend by y axis value, ggpot2

Viewed 280

I am trying to change de legend order of each interaction so we can better understand the country rank of COVD-19 deaths. Is that possible with ggplot2 or we must do this by for loop plots? Anyone can help? Thanks!

library(utils)
library(httr)

GET("https://opendata.ecdc.europa.eu/covid19/casedistribution/csv", authenticate(":", ":", type="ntlm"), write_disk(tf <- tempfile(fileext = ".csv")))
data <- read.csv(tf)
data$dateRep<- as.Date(data$dateRep,"%d/%m/%Y")
seq_datas<- sort(unique(data$dateRep))
seq_paises<- as.vector(unique(data$countriesAndTerritories))
df_final<- data.frame(dateRep = NA, countriesAndTerritories =NA,
                      deaths = NA, acumdeath=NA,cases = NA, dias_diazero=NA )
for(j in seq_paises){
  acum<- subset(data, countriesAndTerritories == j,
                select= c(dateRep,countriesAndTerritories, deaths, cases))
  acum <- acum[order(acum$dateRep, decreasing = FALSE),]
  acum$acumdeath<- cumsum(acum$deaths)
  dia_zero<- acum$dateRep[min(which(acum$cases>0))]
  acum$dias_diazero<- acum$dateRep-dia_zero
  df_final<- rbind(df_final,acum)
}
df_final$dateRep<- as.Date(df_final$dateRep, origin='1970-01-01')
df_final<- df_final[complete.cases(df_final), ]
bra<- subset(df_final, countriesAndTerritories == "Brazil")

require('ggplot2')
require('gganimate')

newdata <- df_final[order(df_final$acumdeath, decreasing = TRUE),]
newdata<- subset(newdata, dateRep == max(df_final$dateRep))
newdata <- newdata[order(newdata$acumdeath, decreasing = TRUE),]
países<- newdata[1:10,2]
newdata<- data.frame()
dados<- data.frame()
for(j in países){
  newdata<- subset(df_final, countriesAndTerritories == j)
  dados<- rbind(newdata,dados)
}
names(bra)<- c("dateRep", "Países", "deaths", "acumdeath", "cases", "dias_diazero")
names(dados)<- c("dateRep", "Países", "deaths", "acumdeath", "cases", "dias_diazero")
dados<- rbind(dados, bra)
grafico <- ggplot(dados, aes(x = dias_diazero, y=acumdeath,
                                colour = Países, label= Países)) +
  geom_point(show.legend = TRUE, alpha = 3) +
  xlim(0, max(dados$dias_diazero)) +
  labs(x = "Dias a partir do primeiro caso confirmado", y = "Mortes Acumuladas COVID 19") +
  scale_size(range = c(10, 12))
scale_color_discrete(breaks = sort(as.numeric(rownames(allEst))))

grafico +  transition_time(as.numeric(dateRep)) +
  shadow_mark(alpha = 0.3, size = 0.5)

Result as gif image

2 Answers

As pointed out by @r2evans, you can reorder your legend by setting the appropriate order of levels.

Here, I use dplyr to sort your values according the acumdeath column using arrange function and then I set factor levels for Paises in function of this order. But you can get the same results using base r function.

Now, when you pass it for ggplot2, your legend is following this order:

library(dplyr)

dados %>% arrange(-acumdeath) %>% 
  mutate(Países = factor(Países, unique(Países))) %>%
  ggplot(aes(x = dias_diazero, y=acumdeath,
                    colour = Países, label= Países)) +
  geom_point(show.legend = TRUE, alpha = 3) +
  xlim(0, max(dados$dias_diazero)) +
  labs(x = "Dias a partir do primeiro caso confirmado", y = "Mortes Acumuladas COVID 19") +
  scale_size(range = c(10, 12))

enter image description here

Does it answer your question ?

NB: Indeed, really nice graph !

Here is the final result using the helpful peers from the StackOverflow community.

sort legend

Once again thanks for the help!

Related