2016-04-14 173 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