将ggplot对象保存为Shiny中的反应对象

时间:2018-02-13 20:12:46

标签: r shiny

我试图在Shiny中创建链接缩放图(通过brushOpts),并按照发布的here示例进行操作。

在我的代码中,我定义了一个反应data.frame,我用它创建(我认为是)一个被动的ggplot()对象,然后发送到renderPlot

# Reactive data.table
dat <- reactive({
    fpath <- paste(basepath, input$lab_name, input$experiment, sep = "/") 

    # some files aren't read - based on the words dataset or eff in the file name
    file_no_suffix <- dir(fpath, full.names = T)[-grep("dataset|eff", dir(ll, full.names = T))]

    # readExpData used fread to read csv file and format it a certain way
    dt <- readExpData(file_no_suffix)

    return(dt)
  }

)

# Reactive ggplot object
plt <- reactive({ggplot(dat())})

# Drop down menu for x-axis of plot
output$dynchoices1 <- renderUI({
    selectInput(inputId = "mainplot_x", label = "Select X-axis", choices = colnames(dat()))
  })

# Drop down menu for y-axis of plot
output$dynchoices2 <- renderUI({
    selectInput(inputId = "mainplot_y", label = "Select Variable to Plot", choices = colnames(dat()))
  })

# Actual plot to display
output$mainplot <- renderPlot({
    mainplt <- plt + geom_point(aes_string(x = input$mainplot_x, y = input$mainplot_y),
                                color = "#003366")
return(mainplt)
})

以上代码在Rstudio控制台中返回freadggplot的错误:

Warning: Error in fread: 'input' must be a single character string containing a file name, 
a command, full path to a file, a URL starting 'http[s]://', 'ftp[s]://' or 'file://', or the input data itself
    102: fread
    101: readClabData [C:/Users/LT11231/Documents/R Directory/readExpData.R#52]
    100: <reactive:dat> [#10]
    ... rest truncated for brevity

Warning: Error in +: non-numeric argument to binary operator
Stack trace (innermost first):
    102: renderPlot [#25]
     92: <reactive:plotObj>
     81: plotOb
    ... rest truncated for brevity

明白错误,显然正在创建dat(),因为colnames(dat() )用于为确定x和y轴的两个choices调用生成selectInput情节 - 我可以看到应用程序中的那些。情节本身不见了:

enter image description here

如果我不单独定义plt并将整个表达式写为

output$mainplot <- renderPlot(ggplot(dat() + 
                                     aes_string(x = input$mainplot_x, y = input$mainplot_y)) + 
                              geom_point()

它工作正常(但仍然会收到fread的警告。)

我不想这样做,因为我希望有几个情节而且我不想为每个这样的实例重写这个代码。

0 个答案:

没有答案