1

I have a plot drawn to visualize the total energy each year like below. I want it to reorder as same as in the dataset (highest producer at the top)

enter image description here

    top10Producers %>%
      ggplot(aes(country_name, totalEnergy_2018, fill= country_name)) +
      geom_bar(stat = "identity", position= "dodge", alpha = 0.5) +
      coord_flip()+
      scale_y_continuous(labels = scales::comma) 

> dput(top10Producers)
structure(list(country = c("DE", "FR", "UK", "TR", "IT", "ES", 
"UA", "SE", "PL", "NO"), country_name = c("Germany", "France", 
"United Kingdom", "Turkey", "Italy", "Spain", "Ukraine", "Sweden", 
"Poland", "Norway"), totalEnergy_2016 = c(619606, 545060.548, 
327223.315, 261937, 281527.826, 267754, 153522, 152650, 152477, 
150066), totalEnergy_2017 = c(624969, 542597.798, 326297.352, 
284257.519, 287091.609, 267167, 146464.8, 160551, 155317.537, 
149799), totalEnergy_2018 = c(578460.796, 560767.871, 319891.625, 
289282.578, 281866, 263080.604, 159072.5, 158287.088, 154498.86, 
150336.105)), row.names = c(NA, -10L), groups = structure(list(
    country = c("DE", "ES", "FR", "IT", "NO", "PL", "SE", "TR", 
    "UA", "UK"), .rows = structure(list(1L, 6L, 2L, 5L, 10L, 
        9L, 8L, 4L, 7L, 3L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, 10L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))
> 
dly
  • 233
  • 1
  • 11

1 Answers1

2

We can use reorder

library(dplyr)
library(ggplot2)
top10Producers %>%
       ggplot(aes(reorder(country_name, totalEnergy_2018), 
              totalEnergy_2018, fill= country_name)) +
       geom_bar(stat = "identity", position= "dodge", alpha = 0.5) +
       coord_flip()+
       scale_y_continuous(labels = scales::comma)

-output

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662