Search code examples
rggplot2forcats

Reorder a boxplot from high to low


I'm stuck with reordering my boxplot from high to low. I've tried to use fct_reorder many times, but i guess i didnt get it rght

My data:

dat <- structure(list(Pesticide = c(
  "Mancozeb", "Mancozeb", "Benomyl",
  "DDT", "Glyphosate", "Carbofuran", "Carbofuran", "Aldicarb",
  "Chlorsulfuron", "Neem", "Oxadiazon", "Oxyfluorfen", "Phorate",
  "Phorate", "Fenvalerate", "Fenvalerate", "BHC", "BHC", "Diallate",
  "Cycloate", "PCA", "Lenacyl", "Phenmedipham", "Aldrin"
), Change = c(
  -11.2,
  -5.6, 33.9, -40, 36.4, -5, -38, -94.6, -16, -49.5, 32.3, 37.5,
  15.9, 22.2, 3.8, 17.6, 27.7, 28.2, 66.3, 33.5, 36, 10.3, 139.8,
  18
)), class = "data.frame", row.names = c(NA, -24L))

My code:

library(ggplot2)
library(tidyverse)
library(ggExtra)
library(forcats)
theme_set(theme_bw())
dat<-read.delim("clipboard")
summary(dat)
q<-qplot (fct_reorder(Pesticide, Change,data=dat, geom=c("boxplot"), 
          fill=Pesticide, xlab="Pesticide", ylab="% Change in Nitrification"))
r<-q + theme(axis.text.x = element_text(angle = 45, hjust = 1))
r+geom_hline(yintercept =0,linetype="dashed",size=0.75,color="red")

Solution

  • Maybe this is what you are looking for. Instead of using qplot I switched to ggplot and do the reordering before passing the data to ggplot.

    Following the comment by @statstew you probably want to map Change on y. Try this:

    library(ggplot2)
    library(dplyr)
    library(ggExtra)
    library(forcats)
    
    theme_set(theme_bw())
    
    dat %>% 
      mutate(Pesticide = fct_reorder(Pesticide, Change)) %>% 
      ggplot(aes(x = Pesticide, y = Change, fill = Pesticide)) +
      geom_boxplot() +
      geom_hline(yintercept =0,linetype="dashed",size=0.75,color="red") +
      labs(x="Pesticide", y="% Change in Nitrification") +
      theme(axis.text.x = element_text(angle = 45, hjust = 1))