-1

I am trying to plot a bar chart that shows CO2 Emissions across European countries. However, I can't seem to order the X axis (i.e. Country) by Y value (CO2 Emissions) from high to low.

I tried using the following code from another topic - I can run it, but nothing actually happens. The X axis is still sorted alphabetically.

ggplot(df, aes(x = reorder(country, -CO2.Emissions), y = CO2.Emissions)) +
    theme(axis.text.x=element_text(angle =- 90, vjust = 0.5)) +
    geom_bar(stat = "identity")

Here is a sample of the data (there are dozens of countries in the original one, and it ranges from 2000 to 2019).

structure(list(iso2c = c("FR", "FR", "FR", "FR", "FR", "GB", 
"GB", "GB", "GB", "GB", "IT", "IT", "IT", "IT", "IT"), country = c("France", 
"France", "France", "France", "France", "United Kingdom", "United Kingdom", 
"United Kingdom", "United Kingdom", "United Kingdom", "Italy", 
"Italy", "Italy", "Italy", "Italy"), CO2.Emissions = structure(c(4.57345972943356, 
5.06217196411801, 5.07506234140888, 5.07791110203759, 5.42898086189895, 
6.49734093050374, 7.10981429361118, 7.35101493770468, 7.07316508167005, 
7.8493651496307, 5.27086678640296, 5.73294187855659, 6.20541385845015, 
6.70255761383033, 6.83837457020099), label = "CO2 emissions (metric tons per capita)"), 
    year = c(2014L, 2013L, 2012L, 2011L, 2010L, 2014L, 2013L, 
    2012L, 2011L, 2010L, 2014L, 2013L, 2012L, 2011L, 2010L)), row.names = c(NA, 
-15L), class = "data.frame")

Any suggestions would be highly appreciated!

This is the output of the original dataset. I'd like to sort the X axis from highest CO2 Emissions to lowest (CO2 Emissions being represesented in the Y axis).

enter image description here

Lactuca
  • 115
  • 2
  • 8
  • I assume that you want to order based on the `max` value of CO2.Emissions for each 'country'. If it is `mean`, then you can change the `.fun` to `mean` in the below solution – akrun Jan 30 '21 at 16:11

1 Answers1

0

We could use fct_reorder with .fun specified as max

library(ggplot2)
library(forcats)
ggplot(df, aes(x = fct_reorder(country, -CO2.Emissions, max),
            y = CO2.Emissions)) +
  theme(axis.text.x=element_text(angle =- 90, vjust = 0.5)) +
  geom_bar(stat = "identity")

-output

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662
  • I copy pasted exactly the same code and I still get the X axis arranged alphabetically... I can run the code, but it just won't reorder the X axis in descending order from highest CO2 Emissions to lowest – Lactuca Jan 30 '21 at 17:00
  • @Lactuca Can you show an example that shows the issue. Your example dput was giving the expected output though – akrun Jan 31 '21 at 12:59