Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the order of the groups in ggplot in R

I am using ggplot to draw a bar chart. How can I change the order of the groups in the bars? In the following example, I want to have type=1984 as the first stack of the bars, then type=1985 on top of 1984 and so on.

  series <- data.frame(
  time = c(rep(1, 4),rep(2, 4), rep(3, 4), rep(4, 4)),
  type = c(1984:1987),
  value = rpois(16, 10)
)

ggplot(series, aes(time, value, group = type)) +
  geom_col(aes(fill= type))

Changing the order using series<- series[order(series$type, decreasing=T),] only changes the order in the legend not in the plot.

like image 330
Hossein Avatar asked Dec 11 '22 05:12

Hossein


2 Answers

Using desc() from dplyr:

ggplot(series, aes(time, value, group = desc(type))) +
    geom_col(aes(fill= type))
like image 63
tmfmnk Avatar answered Dec 15 '22 01:12

tmfmnk


Since ggplot2 version 2.2.1 you don't need to reorder the rows of your data frame to establish the order of the stack in your plot.

So, a pure ggplot approach (as an alternative to tmfmnk's answer) would be:

library(ggplot2)

series %>%
  ggplot(aes(time, value, group=factor(type, levels=1987:1984)))+
  geom_col(aes(fill= factor(type)))+
  guides(fill=guide_legend(title="type"))

As a good practice, I recommend working with factors when plotting your variable type as a categorical one.

Result:

enter image description here

like image 39
allanvc Avatar answered Dec 14 '22 23:12

allanvc