在具有不同 y 轴刻度的 ggplot 中使用 facet_wrap 时的双 y 轴

Dual y-axis while using facet_wrap in ggplot with varying y-axis scale

我正在尝试使用 facet_wrap 在 ggplot2 中绘制多个面板。我想要两个 y 轴。左侧 y 轴范围从 5 到 27,右侧 y 轴范围从 25 到 27。我想用回归线显示所有数据点。但是,当我绘图时,与其他数据集相比,右侧 y 轴的变化较小,因此显示为一条平线。我想将右侧的 y 轴保持在 25 到 27 之间,以便可以清楚地看到数据的变化。我使用了这段代码 1 但无法解决。非常感谢任何帮助。

library(ggplot2)

scaleFactor <- max(d1$weeks) / max(d1$income)

ggplot(mtcars, aes(x=Year)) +
  geom_smooth(aes(y=weeks), method="loess", col="blue") +
  geom_smooth(aes(y=income * scaleFactor), method="loess", col="red") +
  scale_y_continuous(name="weeks", sec.axis=sec_axis(~./scaleFactor, name="income")) +
  theme(
    axis.title.y.left=element_text(color="blue"),
    axis.text.y.left=element_text(color="blue"),
    axis.title.y.right=element_text(color="red"),
    axis.text.y.right=element_text(color="red")
  )

如果这是关于使数据范围重叠而不是仅仅重新缩放最大值,您可以尝试以下操作。

首先我们将创建函数工厂以简化我们的工作:

library(ggplot2)
library(scales)
#> Warning: package 'scales' was built under R version 4.0.3

# Function factory for secondary axis transforms
train_sec <- function(from, to) {
  from <- range(from)
  to   <- range(to)
  # Forward transform for the data
  forward <- function(x) {
    rescale(x, from = from, to = to)
  }
  # Reverse transform for the secondary axis
  reverse <- function(x) {
    rescale(x, from = to, to = from)
  }
  list(fwd = forward, rev = reverse)
}

然后,我们可以使用函数工厂为数据和副轴做转换函数。

# Learn the `from` and `to` parameters
sec <- train_sec(mtcars$hp, mtcars$cyl)

你可以这样申请:

ggplot(mtcars, aes(x=disp)) +
  geom_smooth(aes(y=cyl), method="loess", col="blue") +
  geom_smooth(aes(y= sec$fwd(hp)), method="loess", col="red") +
  scale_y_continuous(name="cyl", sec.axis=sec_axis(~sec$rev(.), name="hp")) +
  theme(
    axis.title.y.left=element_text(color="blue"),
    axis.text.y.left=element_text(color="blue"),
    axis.title.y.right=element_text(color="red"),
    axis.text.y.right=element_text(color="red")
  )
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'

这是一个使用不同数据集的示例。

sec <- train_sec(economics$psavert, economics$unemploy)

ggplot(economics, aes(date)) +
  geom_line(aes(y = unemploy), colour = "blue") +
  geom_line(aes(y = sec$fwd(psavert)), colour = "red") +
  scale_y_continuous(sec.axis = sec_axis(~sec$rev(.), name = "psavert"))

reprex package (v1.0.0)

于 2021-02-04 创建