2

I would like to order my facet_plot plot on two parameters at the same time. I have taken a look here and here but I don't understand how to deal with my two axes use and es.type at the same time.

library(ggplot2)

my.df <- data.frame(site = sample(c("place1","place2"), 20, replace = T), value = sample(1:10,20,replace = T), 
                    use = sample(c("medic","pharma","foodS","forage"), 5, replace = T), es.type = sample(c("plante","cereal","sol","sun"), 5, replace = T))

so my.df can be like :

     site value    use es.type
1  place2     5  medic     sol
2  place2     2 forage     sun
3  place2     2  medic  plante
4  place2     8 pharma  plante
5  place2     8  foodS  cereal
6  place1     9  medic     sol
7  place1     6 forage     sun
8  place2    10  medic  plante
9  place1     8 pharma  plante
10 place1    10  foodS  cereal
11 place1     7  medic     sol
12 place1     3 forage     sun
13 place1     5  medic  plante
14 place2     7 pharma  plante
15 place1     2  foodS  cereal
16 place1     9  medic     sol
17 place2     1 forage     sun
18 place1     2  medic  plante
19 place1     8 pharma  plante
20 place2     8  foodS  cereal    

my plot is

ggplot(data = my.df)+
  geom_bar(aes(x = site, y = value, fill = site), stat="identity")+
  facet_wrap(use~es.type)+
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

enter image description here

I would like to reorder facet and have the max combination first.

Axeman
  • 32,068
  • 8
  • 81
  • 94
delaye
  • 1,357
  • 27
  • 45
  • "max combination" is ambigious. Do you mean the combination of `use` and `es.type`? One of the sites or both? Maybe tell us what order the facets should be in. – Axeman Jun 07 '17 at 08:21
  • Sorry for this ambiguity. I want to play on `use` and `es.type` and have the maximum on both value in first position. – delaye Jun 07 '17 at 08:26

1 Answers1

2

You can try using an interaction eg pasting both variables together.

library(tidyverse)
# Calculate the maximum on both values
gr <- my.df %>% 
  mutate(group=paste(use, es.type, sep="\n")) %>%
  group_by(group) %>% 
  summarise(Max=sum(value)) %>% 
  arrange(-Max)

# Plot the data, but specifiying the order of the facets via
# the factor levels with respect to the order in `gr`.
my.df %>% 
  mutate(group=factor(paste(use, es.type, sep="\n"), levels=gr$group)) %>%
  ggplot()+
  geom_bar(aes(x = site, y = value, fill = site), stat="identity")+
  facet_wrap(~group)+
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

enter image description here

--

In base R you can do before plotting:

my.df$group <- paste(my.df$use, my.df$es.type, sep="\n")
gr <- aggregate(value ~ group, my.df, sum)
gr <- gr[order(gr$value, decreasing = T), ]
my.df$group <- factor(my.df$group, levels = gr$group)
Roman
  • 17,008
  • 3
  • 36
  • 49