【问题标题】:How to return a plotly figure from a function?如何从函数返回一个情节图?
【发布时间】:2020-09-23 11:47:31
【问题描述】:

这里是初学者,所以请温柔! ;)

我在 R 中使用plotly 来生成一些数字。

代码直接在脚本中运行时运行良好,但当我尝试从函数输出plotly 图形时失败。

例如,输入以下内容并直接运行显示图形并且工作正常(data 是一个包含许多不同参数的列表):

fig1 <- plot_ly(x = 0:100, y = data[[parameter]], type = 'scatter', mode = 'lines', line = list(color = 'rgba(191,191,191,0.2)'))
fig1

我有很多情节要做,所以做了如下函数:

Special_plot <- function(data, parameter){fig1 <- plot_ly(x = 0:100, y = data[[parameter]], type = 'scatter', mode = 'lines', line = list(color = 'rgba(191,191,191,0.2)'))
    return(fig1)
}

函数运行,但在显示图形时,我收到一条错误消息:

fig1 <- Special_plot(data, parameter) 
fig1

这是错误信息:

Error: Tibble columns must have consistent lengths, only values of length one are recycled:
* Length 0: Column `y`
* Length 101: Column `x`
Run `rlang::last_error()` to see where the error occurred.

我有很多数字要处理,并且希望避免单独输入每个数字。任何帮助都非常感谢!

【问题讨论】:

  • 欢迎来到 SO!请使用dput 提供示例数据,以便我们重现您的问题。

标签: r r-plotly


【解决方案1】:

我认为您的x 超出了限制。也许尝试更改x 变量,如下所示。此外,R 中不存在 0 索引。因此您必须从 1 开始。

 Special_plot <- function(data, parameter){ fig1 <- plot_ly(x = 1:length(data[[parameter]]), y = data[[parameter]], type = 'scatter', mode = 'lines', line = list(color = 'rgba(191,191,191,0.2)'))
        return(fig1)
    }

fig1 <- Special_plot(data, parameter) 
fig1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2016-05-20
    • 1970-01-01
    • 2016-07-03
    相关资源
    最近更新 更多