【问题标题】:Creating subplot (facets) with custom x,y position of the subplots in ggplot2使用ggplot2中子图的自定义x,y位置创建子图(构面)
【发布时间】:2020-08-05 04:09:06
【问题描述】:

如何自定义 ggplot2 中面板/子图的位置?

具体来说,我有一个分组的时间序列,我想为每个时间序列生成 1 个子图,并带有子图的自定义位置,不一定在网格中。

facet_grid()facet_wrap() 函数不提供对面板位置的完全自定义,因为它使用网格。

library(tidyverse)

df = data.frame(group = LETTERS[1:5],
                x = c(1,2,3,1.5,2.5),
                y =c(2,1,2,3,3),
                stringsAsFactors = F)%>%
  group_by(group)%>%
  expand_grid(time = 1:20)%>%
  ungroup()%>%
  mutate(dv = rnorm(n()))%>%
  arrange(group,time)

## plot in grid          
df%>%                  
ggplot()+
  geom_line(aes(x=time,y=dv))+
  facet_grid(~group)

## plot with custom x, y position
## Is there an equivalent of facet_custom()?             
df%>%                  
ggplot()+
  geom_line(aes(x=time,y=dv))+
  facet_custom(~group, x.subplot = x, y.subplot = y)

仅供参考:此数据集只是一个示例。我的数据是 EEG 数据,其中每组代表一个电极(最多 64 个),我想根据电极在头部的位置绘制每个电极的 EEG 信号。

【问题讨论】:

    标签: r ggplot2 facet-wrap


    【解决方案1】:

    嗯,我想这将不再是一个“平面图”了。因此,我认为那里没有特定的功能。

    但是您可以为此使用出色的 patchwork 包,尤其是 wrap_plots 中的布局选项。

    正如主包作者 Thomas 在小插图中所描述的,使用 area() 的以下选项可能有点冗长,但它会为您提供有关定位所有绘图的完整编程选项。

    library(tidyverse)
    library(patchwork)
    
    mydf <- data.frame(
      group = LETTERS[1:5],
      x = c(1, 2, 3, 1.5, 2.5),
      y = c(2, 1, 2, 3, 3),
      stringsAsFactors = F
    ) %>%
      group_by(group) %>%
      expand_grid(time = 1:20) %>%
      ungroup() %>%
      mutate(dv = rnorm(n())) %>%
      arrange(group, time)
    
    ## plot in grid
    mylist <- 
      mydf %>% 
      split(., .$group) 
    
    p_list <- 
      map(1:length(mylist), function(i){
      ggplot(mylist[[i]]) +
        geom_line(aes(x = time, y = dv)) +
        ggtitle(names(mylist)[i]) 
      }
      )
    
    layout <- c(
      area(t = 1, l = 1, b = 2, r = 2),
      area(t = 2, l = 3, b = 3, r = 4),
      area(t = 3, l = 5, b = 4, r = 6),
      area(t = 4, l = 3, b = 5, r = 4),
      area(t = 5, l = 1, b = 6, r = 2)
    )
    
    wrap_plots(p_list, design = layout)
    
    #> result not shown, it's the same as below
    

    对于更加程序化的方法,一种选择是手动创建所需的“patch_area”对象。

    t = 1:5
    b = t+1
    l = c(1,3,5,3,1)
    r = l+1
    
    list_area <- list(t = t, b = b, l = l, r = r)
    
    class(list_area) <- "patch_area"
    
    wrap_plots(p_list, design = list_area)
    

    reprex package (v0.3.0) 于 2020 年 4 月 22 日创建

    【讨论】:

      猜你喜欢
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多