Home > Mobile >  reorder bar plot by fill in R
reorder bar plot by fill in R

Time:05-14

How to set this plot in ascending order? many thanks in advance.

library(ggplot2)
library(reshape2)
iris2 <- melt(iris, id.vars="Species"); iris2


ggplot(data=iris2, aes(x=Species, y=value, fill=variable)) 
  geom_bar(stat="identity", position="dodge")

CodePudding user response:

You can use reorder to set the bars in ascending overall order :

iris2$variable <- reorder(iris2$variable, iris2$value)

ggplot(data=iris2, aes(x=Species, y=value, fill=variable)) 
  geom_bar(stat="identity", position="dodge")

enter image description here

Notice though that the ordering is the same for all 3 groups, which means that setosa has one bar "out of place".

It is possible, but a lot trickier, to get the bars in ascending order for every species.

library(tidyverse)

iris2 %>%
  group_by(variable, Species) %>%
  summarise(value = max(value)) %>%
  mutate(xval = as.numeric(as.factor(Species))) %>%
  group_by(Species) %>%
  mutate(xval = 0.2 * order(value) - 0.5   xval) %>%
  ggplot(aes(x=xval, y=value, fill=variable)) 
  geom_col(position="dodge", width = 0.2)  
  scale_x_continuous(breaks = 1:3, labels = unique(iris2$Species),
                     name = "Species")

enter image description here

  • Related