r-如何从函数中返回一个绘图图形



这里的初学者,所以请温柔!(

我使用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.

我有很多数字要处理,我希望避免单独键入每个数字。非常感谢您的帮助!

我认为您的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

最新更新