我想生成一个具有以下属性的多面
ggplot
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()
# 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")
# 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
您可以使用
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