按特定值订购ggplot堆叠条形图

时间:2019-11-29 04:31:45

标签: r ggplot2

我正在创建该ggplot图表

# 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")

如何使条形图由“氮”按升序排序?这意味着从左到右的值将反映“氮”值的增加。

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作

# 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