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

如何在R语言散点图函数中自动生成标签并简化参数传递

优化后的散点图函数实现

优化后代码

#### Quick Scatter (Optimized) ####
library(tidyverse)

quick.scatter <- function(x, y) {
  # 自动提取传入变量的名称作为坐标轴标签
  x_label <- deparse(substitute(x))
  y_label <- deparse(substitute(y))
  
  ggplot() +
    geom_point(aes(x = x, y = y), alpha = .4) +
    geom_smooth(aes(x = x, y = y), method = "lm", color = "red") +
    labs(title = "Scatterplot of Data",
         x = x_label,
         y = y_label) +
    theme_bw()
}

关键修改说明

  • 移除原函数的data参数,直接通过x和y接收df$x、df$y这类向量输入
  • 利用deparse(substitute(x))捕获传入变量的原始表达式字符串,自动生成坐标轴标签,无需手动设置
  • 调整ggplot调用逻辑,不再依赖data参数,直接在图层的aes中使用传入的向量

调用示例

quick.scatter(iris$Sepal.Width, iris$Sepal.Length)

调用后x轴会自动显示iris$Sepal.Width,y轴显示iris$Sepal.Length,完全匹配需求。

内容的提问来源于stack exchange,提问作者Shawn Hemelstrand

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:09:23