Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order multiple variables in ggplot2

Tags:

r

ggplot2

I'm attempting to group variables within variables and sort in descending order.

mydf

region  airport value
MIA         FLL 0.244587909
MIA         PBI 0.824144687
MIA         MIA 0.484907626
NYC         EWR 0.731075565
NYC         LGA 0.708648915
NYC         HPN 0.523991258
LAX         LGB 0.651847818
LAX         LAX 0.423607479
LAX         SNA 0.433837044
LAX         ONT 0.723144957
Other   MCO 0.657586674
Other   SJC 0.084138321
Other   OAK 0.698794154
Other   BOS 0.85765002
Other   BNA 0.018953126
Other   WAS 0.234897245

https://i.stack.imgur.com/G1E2k.jpg

enter image description here

I'm trying to reproduce the above graph.

Here is the first attempt:

ggplot(mydf, aes(x=airport,y=value, fill = region)) +  
  geom_bar(stat = "identity")

Here is the 2nd attempt:

ggplot(mydf, aes(x=reorder(airport,-value,sum),y=value, fill = region)) +  
  geom_bar(stat = "identity")

I'm stuck here. Can I nest reorder? reorder(reorder(x, y), y) I'd like not to have to make this a manual process calling out each grouping.

This is as far as I can get

mydf$order <- c('ONT','LGB','SNA','LAX','PBI','MIA','FLL','EWR','LGA','HPN','BOS','OAK','MCO','WAS','SJC','BNA')

ggplot(mydf, aes(x=airport,y=value, fill = region, order = order)) +  
  geom_bar(stat = "identity")

This still doesn't work. I'd appreciate any help!

like image 855
Ryan John Avatar asked May 09 '17 18:05

Ryan John


1 Answers

@eipi10 has a great answer, but I often find myself needing to do that, plus facetting on some other variable, so there are other options as well using the forcats package:

require(dplyr)
require(forcats)

mydf %>% 
  mutate(ordering = -as.numeric(region) + value,
         airport = fct_reorder(airport, ordering, .desc = T)) %>% 
  ggplot(aes(airport, value, fill = region)) + geom_col()

enter image description here

Here's an example of how I might need to use both the ordering and the facets, where I add + facet_grid(~fac, scales = "free_x", space = "free_x") with another column named "fac" with my travel history:

enter image description here

like image 73
Brian Avatar answered Oct 17 '22 12:10

Brian