2017-06-07 39 views
2

我想要在兩個參數上同時訂購我的facet_plot圖。我看了herehere,但我不明白如何在同一時間處理我的兩個軸usees.type通過ggplot2中的模態訂購facet_grid或facet_wrap網格

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)) 

所以my.df可以像:

 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  

我的情節是

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

我想重新排序facet和先有最高的組合。

+0

「最大組合」 是ambigious。你的意思是'use'和'es.type'的組合嗎?其中一個網站或兩者?也許告訴我們應該在什麼樣的順序 – Axeman

+0

對不起,這種含糊不清。我想玩'use'和'es.type',並且在第一個位置上都有最大值。 – delaye

回答

2

您可以嘗試使用交互,例如將兩個變量粘貼在一起。

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

-

在基礎R可以繪製之前做:

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) 
+0

我同意,這可能是最好的方法來解決這個問題。然而,這些方面名稱似乎並不一致,例如'pharma','plante'在哪裏? – Axeman

+0

@Axeman它應該工作。提供的示例數據my.df與問題中粘貼的數據不同。 – Jimbou

+0

哦,現在我明白了。這很混亂! – Axeman