如何在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
相关产品推荐
相关产品推荐

