如何生成每个面上 x 和 y 轴间距相等的分面图,同时允许不同的面比例限制?

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

我想生成一个具有以下属性的多面

ggplot

  • 每个方面可以有不同的比例限制(例如,方面 1 可能采用 0-5 的值,而方面 2 可能采用 100-500 的值) - 所以我希望能够看到这些信息
  • 每个面都有相等的 x 和 y 轴间距(即,如果您使用
    coord_fixed
    ,您会得到什么)

但是,

ggplot
不允许您组合
coord_fixed
facet_wrap(scales = "free")

如果有一个

ggplot
解决方案就好了。它需要是编程式的,而不是手动的,因为我的实际应用程序可能有不同数量的方面和尺度。

Reprex - 我想比较

x
值与
y
值的对齐程度的示例。

# data set-up
library(ggplot2)

dat <- data.frame(
  group = rep(c("A", "B"), each = 5)
  , x = c(1, 2, 3, 4, 5, 100, 200, 300, 400, 700)
  , y = c(1, 2, 3, 4, 10, 100, 200, 300, 400, 500)
)

# this has the same aspect ratio on x and y
# but I can't see any detail in group A
ggplot(data = dat) +
  geom_point(aes(x = x, y = y)) +
  facet_wrap(~ group) +
  geom_abline(slope = 1, intercept = 0, colour = "red") +
  coord_fixed()

enter image description here

# I can see detail in both groups
# but now the aspect ratios are off 
ggplot(data = dat) +
  geom_point(aes(x = x, y = y)) +
  facet_wrap(~ group, scales = "free") +
  geom_abline(slope = 1, intercept = 0, colour = "red")

enter image description here

# manual option - this is the kind of thing I want
# but I don't actually want to have to code this manually
library(patchwork)
g1 <- ggplot(data = dat[dat$group == "A",],) +
  geom_point(aes(x = x, y = y)) +
  geom_abline(slope = 1, intercept = 0, colour = "red") +
  labs(title = "A") +
  coord_fixed()
g2 <- ggplot(data = dat[dat$group == "B",],) +
  geom_point(aes(x = x, y = y)) +
  geom_abline(slope = 1, intercept = 0, colour = "red") +
  labs(title = "B") +
  coord_fixed()
g1 + g2

enter image description here

r ggplot2 visualization
1个回答
0
投票

您可以使用

facetted_pos_scales
包中的
ggh4x
函数来完成此操作。

# data set-up
library(tidyverse)
library(ggh4x)
#> 
#> Attaching package: 'ggh4x'
#> The following object is masked from 'package:ggplot2':
#> 
#>     guide_axis_logticks

dat <- data.frame(
  group = rep(c("A", "B"), each = 5)
  , x = c(1, 2, 3, 4, 5, 100, 200, 300, 400, 700)
  , y = c(1, 2, 3, 4, 10, 100, 200, 300, 400, 500)
)

# Find common limits
df.lims = dat %>% 
  summarise(lims = list(c(lo = min(union(x, y)), hi = max(union(x, y)))), .by = group)
lims_list = df.lims$lims %>% setNames(df.lims$Protein)
scale_x_list = lapply(lims_list, function(x) scale_x_continuous(limits = x))
scale_y_list = lapply(lims_list, function(x) scale_y_continuous(limits = x))

# Plot
p = ggplot(data = dat) +
  geom_point(aes(x = x, y = y)) +
  facet_wrap(~ group, scales = "free") +
  geom_abline(slope = 1, intercept = 0, colour = "red")

p + facetted_pos_scales(x = scale_x_list, y = scale_y_list)

创建于 2024 年 12 月 19 日,使用 reprex v2.0.2

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