2016-04-14 28 views
4

我想在我的數據中顯示兩個維度,(1)報告不同面的實體和(2)與x軸上的數據點關聯的國家/地區。問題在於,國家層面包含一個「總量」,比所有單個值高很多,所以我需要一個自己的軸限制。ggplot2:構面:不同的軸限制和可用空間

我的解決方案是嘗試另一個刻面維度,但我無法使其工作並在同一時間很好地查找。請看下面的僞數據:

id <- c(1,1,1,1,1,1,2,2,2,2,2,2) 
country <- c("US","US","UK","World","World","World","US","US","UK","World","World","World") 
value <- c(150,40,100,1000,1100,1500,5,10,20,150,200,120) 
# + some other dimensions 
mydat <- data.frame(id,country,value) 

    id country value 
1 1  US 150 
2 1  US 40 
3 1  UK 100 
4 1 World 1000 
5 1 World 1100 
6 1 World 1500 
7 2  US  5 
8 2  US 10 
9 2  UK 20 
10 2 World 150 
11 2 World 200 
12 2 World 120 

如果我使用一個小網格,以顯示世界總量中,軸的限位被迫對其他國家以及:

mydat$breakdown <- mydat$country == "World" 

ggplot(mydat) + aes(x=country,y=value) + geom_point() + 
    facet_grid(id ~ breakdown,scales = "free",space = "free_x") + 
    theme(strip.text.x = element_blank() , strip.background = element_blank(), 
     plot.margin = unit(c(0,0,0,0) , units = "lines")) 

(的最後一部分情節只是刪除額外的地帶)。

facet grid plot

如果我用一個小包裹,但它給我的每一個情節不同軸的限制,但我不能通過space = "free_x"的說法,這意味着總的單柱將消耗相同的空間整個國家的概述,它看起來醜陋的數據集與許多國家:

ggplot(mydat) + aes(x=country,y=value) + geom_point() + 
    facet_wrap(id ~ breakdown,scales = "free") 

facet wrap plot

這裏還有幾個線程這問類似的問題,b但沒有任何答案幫助我實現這一目標。

Different axis limits per facet in ggplot2

Is it yet possible to have different axis breaks/limits for individual facets in ggplot with free scale?

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

回答

4

也許嘗試gridExtra::grid.arrangecowplot::plot_grid

lst <- split(mydat, list(mydat$breakdown, mydat$id)) 
plots <- lapply(seq(lst), function(x) {ggplot(lst[[x]]) + 
    aes(x=country,y=value) + 
    geom_point() + 
    ggtitle(names(lst)[x]) + labs(x=NULL, y=NULL) 
}) 
do.call(gridExtra::grid.arrange, 
     c(plots, list(ncol=2, widths=c(2/3, 1/3)), 
      left="Value", bottom="country")) 

enter image description here

+1

這很好,謝謝!短短數增加,使其非常好的: (1) 刪除前綴: - ( 「真」, 「」,名稱(LST)) '名(LST) Chris7b

+0

你可能還想看看'cowplot :: plot_grid',它可以讓你對齊座標軸:https://cran.r-project.org/web/packages/cowplot/vignettes/introduction.html – lukeA

相關問題