【问题标题】:ggplot2: facets: different axis limits and free spaceggplot2:方面:不同的轴限制和可用空间
【发布时间】:2016-04-14 13:50:19
【问题描述】:

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

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

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 wrap,它确实为每个图提供了不同的轴限制,但是我无法传递 space = "free_x" 参数,这意味着总计的单列将占用与整个国家/地区概览相同的空间,这对于包含许多国家/地区的数据集来说看起来很丑:

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

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

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    也许可以试试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"))
    

    【讨论】:

    • 太好了,谢谢!!只需添加一些内容就可以使它非常好:(1)删除前缀:names(lst) &lt;- gsub("TRUE.","",names(lst))names(lst) &lt;- gsub("FALSE.","",names(lst))。 (2) 使列宽动态化:t &lt;- length(unique(mydat$country[mydat$breakdown]))f &lt;- length(unique(mydat$country[!(mydat$breakdown)])),然后将列宽替换为f/(t+f)t/(t+f)。可能有更有效的方法可以做到这一点,但我仍然从 R 开始(ggplot 是从 Matlab 切换的原因之一 :))。
    • 您可能还想查看cowplot::plot_grid,它允许您对齐轴:cran.r-project.org/web/packages/cowplot/vignettes/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多