ggh 4x::facet_grid2()-有没有办法在x轴上有自由和独立的刻度,但列显示相同的刻度?

elcex8rz  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(71)

我使用ggh4x包的facet_grid2()功能,facetting上的2个变量(一个用于行,一个用于行)。y轴上的值不同,x轴的范围也不同,所以我使用scales="free"参数。我希望我的每个面显示不同的x轴,所以我使用了参数independent="x"。有没有一种方法可以让x轴的值对每一行都是独立的,但是在两列之间显示的范围是一致的?
下面是一个可重现的示例来解决该问题:

iris <- iris %>% 
  mutate(group1 = rep(c("w","x","y","z"), each=20, length.out=nrow(iris)),
         group2 = rep(c("A","B"), length.out=nrow(iris)))

ggplot(iris,
       aes(x=Sepal.Length,
           y=group1)) +
  geom_point() +
  facet_grid2(Species~group2, 
              scales = "free",
              independent = "x")

字符串
我的理想结果是第一行的x轴显示两列的范围为4.4-5.6,第2行(两列)为5-7,第3行(两列)为5-8。
谢谢你,谢谢

yyyllmsg

yyyllmsg1#

另一种选择是使用ggh4x::scales_x_facetggh4x::facetted_pos_scales,这两种方法都允许为每个或一组面板单独设置比例:

library(ggplot2)
library(ggh4x)

ggplot(
  iris,
  aes(
    x = Sepal.Length,
    y = group1
  )
) +
  geom_point() +
  facet_grid2(Species ~ group2,
    scales = "free_x",
    independent = "x"
  ) +
  scale_x_facet(
    Species %in% "setosa", limits = c(4.4, 5.6)
  ) +
  scale_x_facet(
    Species %in% "versicolor", limits = c(5, 7)
  ) +
  scale_x_facet(
    Species %in% "virginica", limits = c(5, 8)
  )

字符串
x1c 0d1x的数据

EDIT或者不复制代码,可以使用例如purrr::map系列函数来创建list刻度,如@eipi10在他的评论中所建议的:

library(ggplot2)
library(ggh4x)
library(purrr)

scale_x <- iris |>
  split(~Species) |>
  map(~range(.x$Sepal.Length)) |> 
  imap(
    ~ scale_x_facet(
      Species == .y,
      limits = .x
    )
  )

p <- ggplot(
  iris,
  aes(
    x = Sepal.Length,
    y = group1
  )
) +
  geom_point() +
  facet_grid2(Species ~ group2,
              scales = "free_x",
              independent = "x"
  ) + 
  scale_x


wvyml7n5

wvyml7n52#

按行控制x轴范围的一种方法是为每行创建单独的小平面图,然后将它们合并合并。(行变量)。然后我们使用mapSpecies的每个水平创建一个多面图。在map中,我们得到x-对于给定的Species水平,Sepal.Width的范围,并使用它来设置每个图的x轴限制。然后我们使用patchwork::wrap_plots()来合并组合图。

library(tidyverse)
library(patchwork)

iris <- iris %>% 
  mutate(group1 = rep(c("w","x","y","z"), each=20, length.out=nrow(iris)),
         group2 = rep(c("A","B"), length.out=nrow(iris)))

# Create a list of plots, one for each level of Species
p = iris %>% 
  group_by(Species) %>% 
  group_split() %>% 
  map(~{

    # Get x-axis range for the current plot
    rng = range(.x[["Sepal.Length"]])

    ggplot(.x, aes(x=Sepal.Length, y=group1)) +
      geom_point() +
      facet_grid(Species~group2) +
      scale_x_continuous(limits=rng) 
  })

p[1:2] = p[1:2] %>% map(~.x + labs(x=NULL))
p[c(1,3)] = p[c(1,3)] %>% map(~.x + labs(y=NULL))

wrap_plots(p, ncol=1)

字符串
x1c 0d1x的数据
创建于2023-12-08带有reprex v2.0.2

相关问题