【问题标题】:ggplot2 facet_grid with facet titlesggplot2 facet_grid 带有构面标题
【发布时间】:2020-10-13 20:24:12
【问题描述】:

facet_grid 中添加分面标题是否有规范的方法?或者facet_wrap 中特定行标签的方法? (没有geom_textgeom_label 或 grob 操作。)

考虑:

dat <- data.frame(rowInd = paste0("R", c(1, 2, 2, 3, 3, 3)), colInd = paste0("C", c(1, 1, 2, 1, 2, 3)),
                  facetName = c("1-10", "60-70", "80-90", "100-110", "120-130", "140-150"), val=1:6)
dat
#   rowInd colInd facetName val
# 1     R1     C1      1-10   1
# 2     R2     C1     60-70   2
# 3     R2     C2     80-90   3
# 4     R3     C1   100-110   4
# 5     R3     C2   120-130   5
# 6     R3     C3   140-150   6

直接地块给出:

library(ggplot2)
ggplot(dat, aes(x=1, y=val)) + facet_grid(rowInd ~ facetName, switch="y") # 1
ggplot(dat, aes(x=1, y=val)) + facet_wrap(rowInd ~ facetName)             # 2
ggplot(dat, aes(x=1, y=val)) + facet_grid(rowInd ~ colInd, switch="y")    # 3

地点:

  1. 包括我想要的行和分面标签,但并非所有分面标签都适用于所有行;
  2. 正确地将行标签 ("R1") 与构面标签相关联,每个构面一个标签,但失去构面之间的行从属关系;
  3. 丢失分面标签。

最终,我正在尝试做类似于以下之一的事情:

如果需要,我可以“填写”数据(也许是为了便于绘制正确的图),尽管让它们自动空心图或空白空间会很棒。

【问题讨论】:

  • 可能最简单的创建右侧图的方法是合并 3 个图,每行 1 个。
  • 是的,对不起,这也是我试图避免的事情,但这也是一种选择。谢谢,@Axeman。

标签: r ggplot2 facet facet-wrap facet-grid


【解决方案1】:

因为您没有明确排除“拼凑”选项...跟随 Axeman 的领导,这里尝试将其自动化。

我知道这有点 hacky,并且 y 标签会重复出现(当然需要一些调整),而且它肯定不是“规范的”,但放在一起很有趣...... :)

library(tidyverse)
library(patchwork)
dat <- data.frame(rowInd = paste0("R", c(1, 2, 2, 3, 3, 3)), colInd = paste0("C", c(1, 1, 2, 1, 2, 3)),
                  facetName = c("1-10", "60-70", "80-90", "100-110", "120-130", "140-150"), val=1:6)

ls_p <- 
  dat %>% 
  mutate(row_facet= paste(rowInd, facetName, sep = "_")) %>%
  split(., .$row_facet) %>%
  purrr::map(., .f = ~ {
    ggplot(., aes(x=1, y=val)) + facet_grid(rowInd ~ facetName, switch = "y")})

split_ls <- split(ls_p, dat$rowInd)

lengths_rowInd <- lengths(split_ls) 
col_len <- max(lengths_rowInd)
lengths_empty <- col_len - lengths_rowInd

p_empty <- ggplot() + theme_void()
ls_empty_p <- lapply(lengths_empty, function(x) rep(list(p_empty), x))

ls_filled_p <- Map(append, split_ls, ls_empty_p)
new_list <- do.call(list, unlist(ls_filled_p, recursive=FALSE))

wrap_plots(new_list)

reprex package (v0.3.0) 于 2020-06-23 创建

【讨论】:

  • 既然你提到了patchwork(对我来说是新的),你可能会做三个图(而不是这里的六个),然后用p1 / p2 / p3(尽管有间隔)堆叠它们......很好的推荐,谢谢你
  • ...但是现在我在这里看到了您的疯狂方法...theme_void() 是一个不错的选择。
  • 我一直在尝试更优雅和与主题无关的东西,这样我就可以(尽可能)在其中和周围继续使用ggplot2-methods。
  • 现在只是ggplot() 创建一个空的情节,不应该需要一个主题(我想?)。另请参阅 patchwork::plot_spacer 了解定义空图的正式方式,因为您已经在使用 patchwork
  • @Axeman 谢谢!我尝试了 ggplot() 但正在绘制灰色区域。我不确定如何在上述方法中使用 plot_spacer,但很高兴知道它,我不知道 :)
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 2013-03-29
相关资源
最近更新 更多