首页 文章

ggplot2:facets:不同的轴限制和自由空间

提问于
浏览
5

我想在我的数据中显示两个维度,(1)不同方面的报告实体和(2)与x轴上的数据点相关联的国家 . 问题是国家维度包括一个“总数”,它比所有单个值都高很多,所以我需要一个自己的轴限制 .

我的解决方案是尝试另一个facetting维度,但我无法让它工作,同时看起来很好 . 考虑以下虚拟数据:

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

如果我使用facet wrap,它确实为每个绘图提供了不同的轴限制,但是我无法传递 space = "free_x" 参数,这意味着总数的单个列将占用与整个国家概述相同的空间,这看起来很难看许多国家/地区的数据集:

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

facet wrap plot

这里有几个线程提出类似的问题,但没有一个答案帮助我实现这一目标 .

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

1 回答

  • 5

    也许试试 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

相关问题