【问题标题】:how to pass an arguments to function to get a line plot using ggplot2?如何将参数传递给函数以使用 ggplot2 获取线图?
【发布时间】:2017-11-02 11:17:39
【问题描述】:

我正在尝试编写一个函数来创建时间序列图(折线图)。如何将参数传递给函数以创建绘图?我尝试了不同的方法,例如使用aes_string 等,但没有成功。

lineplotfun <- function(feature){
  ggplot(aes(x = 1:length(feature), y = feature), data = mtcars) +
  geom_line()
  }

lineplotfun(mpg)

我想将mpg 作为字符串或名称传递。

【问题讨论】:

  • 您的意思是lineplotfun(mtcars$mpg)?因为这样可以正常工作,所以您可以将错误编码出来。
  • 你想在参数中传递什么?变量的名称?数据向量?数据框?

标签: r function ggplot2 environment


【解决方案1】:

问题中的代码存在许多问题。

1) y 不在aes()

2) 如果加载了ggplot2,则mpgtibble

3) y = featuredata = mtcars 没有意义

4) 1:length(feature) 仅在 feature 是向量时才有意义

实现您想要的一种方法是设置data = NULL并将向量传递给函数:

lineplotfun <- function(feature){
  require(ggplot2)
  ggplot2::ggplot(data = NULL, aes(x = seq_along(feature), y = feature)) +
    ggplot2::geom_line()
}

lineplotfun(mtcars$mpg)

结果是:

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 2019-01-19
    • 1970-01-01
    • 2022-11-25
    • 2012-09-24
    • 2015-10-30
    • 1970-01-01
    • 2014-06-04
    相关资源
    最近更新 更多