0
votes

I'm trying to order a stacked geom_bar or geom_col by the height of the bars but arranging my dataset or using "reorder()" inside the aesthetics of ggplot is not working, so looking for some help. This is my dataset

df
Roost  NGen Sex  
   <chr> <int> <chr>
 1 A1        2 unkwn
 2 A1        3 M    
 3 A1       10 F    
 4 A2        2 M    
 5 A2        3 F    
 6 AA1      12 unkwn
 7 AA1      24 M    
 8 AA1      29 F    
 9 AC-01     4 M    
10 AC-01     5 unkwn

When i plot it using:

ggplot(df, aes(x= Roost, y= NGen, fill= Sex))+ geom_col()+  coord_flip()

The bars are ordered by the name of the roost and not the height of the bars

Picture on this link 1: https://i.stack.imgur.com/cS7SB.png (i can't insert pictures as i do not have enough "reputation" points as a new user.)

I have tried the following code to try to organise the columns by height

ggplot(df, aes(x= reorder(Roost,NGen), y= NGen, fill= Sex))+ geom_col()+  coord_flip()

The code does organise the data in some fashion generating the following graph

enter image description here

However, as you can see the bars are not organised by height. The outcome is the same if i use geom_bar or geom_col.

I have also tried converting Roost into factors and converting NGen to numeric and using aes(x= fct_reorder(Roost,NGen), y= NGen, fill= Sex) but I haven't got the desired outcome.

Any clues are greatly appreciated

Cheers,

Diana

1

1 Answers

0
votes

Calculate the sum of NGen for each Roost, arrange the data based on sum, assign factor levels and then plot the data.

library(dplyr)
library(ggplot2)

df %>%
  group_by(Roost) %>%
  mutate(NGen_s = sum(NGen)) %>%
  ungroup %>%
  arrange(NGen_s) %>%
  mutate(Roost = factor(Roost, unique(Roost))) %>% 
  ggplot(aes(x= Roost, y= NGen, fill= Sex)) + 
  geom_col() +  coord_flip()