首页 > 解决方案 > 从 R 中的另一个工作表调用图形

问题描述

我的 Shiny 应用程序有点长,因为我在多个面板中绘制了各种图表。因此,为了帮助一些组织,我想知道是否可以将图形代码移动到单独的 r 脚本中,并从原始 r 脚本中调用这些图形。

更复杂的是,我想显示的图表都需要用户从 Shiny 应用程序输入。

是否可以使用 R 中另一个脚本的代码来绘制图形,如果可以,如何绘制?此外,由于会有多个图,是否可以指定新 r 脚本中的哪个图将放在指定位置,或者我需要为每个图创建一个单独的 r 脚本(这会破坏加强组织监督)?

我编写了一些简化的、可重现的代码(见下文),希望能让您了解我在寻找什么。本质上,我希望在 renderPlot() 中生成图形的任何代码都来自单独的 r 脚本。

非常感谢您的帮助!

library(shiny)

ui <- fluidPage(
  mainPanel(
    selectInput("input1","Select an option",choices = c("First","Second")),
    plotOutput("plot1"),
    plotOutput("plot2")
  )
)

server <- function(input, output, session) {
  output$plot1 = renderPlot({
    if(input$input1=="First"){
      ##This is where I'd like to call the code for the graph from another sheet.
      plot(1,main = input$input1)
    }
    if(input$input1=="Second"){
      ##Again, this is where I'd like to code for the graph from another sheet.
      plot(2,main = input$input1)
    }
  })

  output$plot2 = renderPlot({
    if(input$input1=="First"){
      ##This is where I'd like to call the code for the graph from another sheet.
      plot(1*rnorm(1,10,2),main = input$input1)
    }
    if(input$input1=="Second"){
      ##Again, this is where I'd like to code for the graph from another sheet.
      plot(2*rnorm(1,50,2),main = input$input1)
    }
  })


}

shinyApp(ui, server)


标签: rggplot2graphshiny

解决方案


您可以创建一个函数,该函数为您制作的绘图提供参数,例如数据和绘图标题,然后将这些参数传递给创建绘图的代码。例如,假设唯一改变的是 x 和绘图标题,您可以定义一个接受这些参数的函数,然后在代码中使用它们来制作绘图。然后你把它保存在一个单独的脚本中,并source()在你的闪亮应用程序中调用脚本。

地块.R

plot_data <- function(x, y=NULL, plot.title){

  if(is.null(y)) {
    y <- seq(from = 1, by = 1, length.out = length(x))
  }

  plot(x, y, main = plot.title)

}

使用 将函数加载到全局环境中source('plots.R'),确保 plots.R 保存在与闪亮应用相同的位置。

library(shiny)

source("plots.R")

ui <- fluidPage(
  mainPanel(
    selectInput("input1","Select an option",choices = c("First","Second")),
    plotOutput("plot1"),
    plotOutput("plot2")
  )
)

server <- function(input, output, session) {
  output$plot1 = renderPlot({
    if(input$input1=="First"){
      ##This is where I'd like to call the code for the graph from another sheet.
      plot_data(1, plot.title = input$input1)
    }
    if(input$input1=="Second"){
      ##Again, this is where I'd like to code for the graph from another sheet.
      plot_data(2, plot.title = input$input1)
    }
  }) 

  output$plot2 = renderPlot({
    if(input$input1=="First"){
      ##This is where I'd like to call the code for the graph from another sheet.

      plot_data(1*rnorm(1,10,2),plot.title = input$input1)

    }
    if(input$input1=="Second"){
      ##Again, this is where I'd like to code for the graph from another sheet.
      plot_data(2*rnorm(1,50,2),plot.title = input$input1)
    }
  })


}

shinyApp(ui, server)

当然,这看起来差别不大,但是对于跨越多行的复杂绘图,将绘图代码转换为函数会将多行转换为一行。


推荐阅读