如何解决双 y 轴,同时在 ggplot 中使用 facet_wrap 并具有不同的 y 轴比例
我正在尝试在使用 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),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)),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 年 2 月 4 日创建
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。