0

I'm creating this ggplot chart

# library
library(ggplot2)

# create a dataset
specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 4)
value <- abs(rnorm(12 , 0 , 15))
data <- data.frame(specie,condition,value)

# Stacked + percent
ggplot(data, aes(fill=condition, y=value, x=specie)) + 
    geom_bar(position="fill", stat="identity")

How can I make it so that the barchart is order by "nitrogen" in ascending order? Meaning that values from left to right will reflect the increase of the value "nitrogen".

EGM8686
  • 1,492
  • 1
  • 11
  • 22

1 Answers1

1

You can do the following

# Order factor levels by increasing "Nitrogen" values.
lvls <- with(
    subset(data, condition == "Nitrogen"),
    specie[order(value, decreasing = TRUE)])
data <- transform(data, specie = factor(specie, levels = lvls))

# Stacked + percent
ggplot(data, aes(fill=condition, y=value, x=specie)) +
    geom_bar(position="fill", stat="identity")

enter image description here

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68