如何在 ggplot2 R 中为分面数据指定多个 xlims?

How to specify multiple xlims for facetted data in ggplot2 R?

数据由两个变量分面(见图)。每个变量都有不同的范围。我想指定范围,以便 var1 和 vae2 中的所有图都受这些变量的最小值和最大值约束。请参阅随附的示例代码。我不想在 facet_wrap 上使用 setscales = "free"

var1 <- rnorm(100, 6, 2)
var2 <- rnorm(100,15,2)
spp.val <- rnorm(100,10,2)
spp <- rep(c("A","B","C","D"), 25)

df <- data.frame(var1, var2,spp, spp.val)

df <- gather(df,
key = "var",
value = "var.val",
var1,var2)

df$var <- as.factor(as.character(df$var))
df$spp <- as.factor(as.character(df$spp))

ggplot(aes(x = var.val, y = spp.val), data = df) +
  geom_point() +
  facet_grid(spp~var)

#I want the limits for each facet_grid to be set as follows
xlim(min(df[df$var == "var1",]), max(df[df$var == "var1",])
xlim(min(df[df$var == "var2",]), max(df[df$var == "var2",])

这是你想要的吗?

library(tidyverse)

tibble(
  var1 = rnorm(100, 6, 2),
  var2 = rnorm(100, 15, 2),
  spp.val = rnorm(100, 10, 2),
  spp = rep(c("A", "B", "C", "D"), 25)
) |> 
  pivot_longer(starts_with("var"), names_to = "var", values_to = "var.val") |> 
  mutate(across(c(spp, var), factor)) |> 
  ggplot(aes(var.val, spp.val)) +
  geom_point() +
  facet_grid(spp ~var, scales = "free_x")

reprex package (v2.0.1)

于 2022-04-23 创建