Home > front end >  How to order barplot by variable within fill in ggplot 2
How to order barplot by variable within fill in ggplot 2

Time:11-15

So I'm fixing a graph I found on the internet about men's and women's smoking rates in various countries, and I want to order it by men's smoking rates.

What I have here orders by men's smoking rates women's smoking rates

countries <- c("China","Russia","Turkey","Greece","Israel","Germany","France",
              "Italy","Canada","United Kingdom","United States","India","Australia",
              "Brazil","Sweden")
women_rate <- c( 1.6,11.3,14.4, 17.9,12.6,18.6,15.4,12.7,12.3,12.5,12.7,1.7,10.4,7.3,6.8)

men_rate <- c(44.4,43.9,40.6,29.9,27.3,25.4,20.5,20.5,17.3,15.9,15.3,15.2,12.8,12.7,5.9)

country <- rep(countries, 2)
rate <- c(men_rate,women_rate)
gender <- c(rep("men",length(men_rate)),rep("women",length(women_rate)))

smoking_data <- data.frame(country,rate,gender)


library(tidyverse)
library(ggthemes)




ggplot(smoking_data, aes(x=rate,
                         y=reorder(country,rate),fill=gender))  
  geom_bar(position='dodge', stat='identity')

And it gives this resulting graph.

enter image description here

I want it to be ordered by men's smoking rates so China, Russia, Turkey, Greece, etc.

CodePudding user response:

By default reorder will order by the mean of all obs. per group, i.e. in your case the mean of men and women per country.

One fix would be to use a "helper column" where the values for women are replaced by NA so that only men values are taken into account when reordering. This could for example achieved by using reorder(country, ifelse(gender == "men", rate, NA), na.rm = TRUE):

library(ggplot2)

ggplot(smoking_data, aes(
  x = rate,
  y = reorder(country, ifelse(gender == "men", rate, NA), na.rm = TRUE), fill = gender
))  
  geom_bar(position = "dodge", stat = "identity")

enter image description here

  • Related