You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于ggproto开发自动配置log10双轴的ggplot2扩展

可实现该扩展,无需重写复杂ggproto逻辑

ggplot2原生支持将多个图层、刻度组件打包为单个自定义函数,直接透传所有原生参数,即可实现一行代码替换geom_smooth()+双轴log10变换的效果。

实现代码

library(ggplot2)

geom_smooth_log10 <- function(..., x_scale_args = list(), y_scale_args = list()) {
  list(
    # 透传所有geom_smooth原生参数
    geom_smooth(...),
    # 合并默认log10变换与用户自定义刻度参数
    do.call(scale_x_continuous, c(list(trans = "log10"), x_scale_args)),
    do.call(scale_y_continuous, c(list(trans = "log10"), y_scale_args))
  )
}

使用方法

和原生geom_smooth()用法完全一致,支持传入所有geom_smooth()的原生参数(比如拟合方法、颜色、置信区间开关、线宽等),也可以通过x_scale_args、y_scale_args自定义坐标轴的名称、刻度、标签等属性。
用提供的测试数据运行示例:

set.seed(11) # 生成随机数据
method1 = c(rnorm(19,0,1),2.5)
method2 = c(rnorm(19,0,1),2.5)
df_corr <- data.frame(first = method1, second = method2) 

ggplot(data = df_corr, mapping = aes(x = first, y = second)) +
  geom_point(alpha = 0.5) + # 额外添加散点层展示原始数据
  # 一行调用即可实现平滑层+双轴log10变换,直接传geom_smooth的自定义参数
  geom_smooth_log10(color = "#2c3e50", fill = "#3498db", linewidth = 1)

注意事项

  • 该实现为ggplot2官方支持的组件打包方案,兼容性优于重写ggproto的实现,所有geom_smooth、scale_x_continuous、scale_y_continuous的原生参数都可以正常透传
  • 示例模拟数据存在负值,运行时会弹出log10变换产生缺失值的警告,实际使用时保证x、y轴映射变量均为正数值即可消除警告
  • 如果需要自定义坐标轴属性,比如修改x轴名称、设置刻度点,可以按如下方式传参:
    geom_smooth_log10(
      method = "lm",
      x_scale_args = list(name = "第一个变量(log10)", breaks = c(0.1, 1, 10)),
      y_scale_args = list(name = "第二个变量(log10)", limits = c(0.01, 10))
    )
    

内容的提问来源于stack exchange,提问作者Sam Min

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 22:57:33