使用`coord_flip`和`facet_nested`

问题描述 投票:0回答:1

这是一个 MWE:

这是一些数据:

data <- 
structure(list(cilow = c(0.0528306698161456, 0.0708961798923575, 
-0.0860844842473584, 0.149293656874665, 0.175348742108531, 0.00150087452513042
), fullest = c(0.194641049761067, 0.282228250041396, 0.107053849480737, 
0.296390973553158, 0.38517505087032, 0.205531742216253), cihigh = c(0.336451429705988, 
0.493560320190435, 0.300192183208833, 0.443488290231651, 0.595001359632109, 
0.409562609907376), regressor = c("1. Plant 1", "2. Plant 2", 
"3. Plant 3", "4. Plant 4", "5. Plant 5", "6. Plant 6"), group = c("A. Green", 
"A. Green", "A. Green", "B. Blue", "B. Blue", "C. Red"), title = c("(i) Flowers", 
"(i) Flowers", "(i) Flowers", "(i) Flowers", "(ii) Trees", "(ii) Trees"
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))

这是我迄今为止尝试过的:

ggplot(data, aes(forcats::fct_rev(regressor), fullest)) +
    geom_hline(yintercept = 0, linetype = "dashed", size = 0.3) +
    geom_errorbar(
      aes(ymin = cilow, ymax = cihigh),
      width = 0, size = 0.8) +
    geom_point(
      show.legend = F) +
    theme_bw() +
    facet_nested(. ~ group + title, scales = "free", space = "free")
    facet_wrap(. ~ group, cols = 1)

我想翻转它,使得有 1 列 3 个面,彼此堆叠在一起。第一级“组”构面标题应该是水平的并且位于每个构面的顶部。第二级标题(“标题”)应该是垂直的,并连接左侧的相关面。 “回归器”名称应位于右侧。有没有办法通过嵌套标题实现这种坐标翻转?

r ggplot2 visualization facet-grid
1个回答
0
投票

这里有一些使用拼凑和半手动定义的子图的技巧。

library(tidyverse)
library(patchwork)

plot_facet <- function(df, grp_no) {
  df |>
    group_by(group) |>
    filter(group_indices() == grp_no) |>
ggplot(aes(forcats::fct_rev(regressor), fullest)) +
  geom_hline(yintercept = 0, linetype = "dashed", size = 0.3) +
  geom_errorbar(
    aes(ymin = cilow, ymax = cihigh),
    width = 0, size = 0.8) +
  geom_point(
    show.legend = F) +
  theme_bw() +
  labs(x = NULL) +
  ggh4x::facet_nested(group ~ title, scales = "free", space = "free")
}


plot_facet(data, 1) /
  plot_facet(data, 2) /
  plot_facet(data, 3)

enter image description here

更内置的(

ggh4x::facet_nested
)是将组和标题标题放在绘图的同一区域:

ggplot(data, aes(forcats::fct_rev(regressor), fullest)) +
  geom_hline(yintercept = 0, linetype = "dashed", size = 0.3) +
  geom_errorbar(
    aes(ymin = cilow, ymax = cihigh),
    width = 0, size = 0.8) +
  geom_point(
    show.legend = F) +
  theme_bw() +
  ggh4x::facet_nested(group + title~., scales = "free", space = "free")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.