簡體   English   中英

如何在Shiny中模塊化一個簡單的條形圖?

[英]How to modularize a simple bar plot in Shiny?

這是我的應用程序代碼:

應用程序

library(shiny)

source("func.R")

# create data
name <- c("Moller", "Mayer", "Bernard")
sales <- c(35000, 40000, 60000)
df <- data.frame(name, sales)

# app
server <- function(input, output, session) {
  x <- callModule(testPlot, "test", data = reactive(df), xAxis = reactive("name"), yAxis = reactive("sales"))
}
ui <- fluidPage(
  testPlotUI(id = "test", stringName = "test")
)

shinyApp(ui = ui, server = server)

這是我的模塊代碼:

功能

library(shiny)
library(ggplot2)

testPlotUI <- function(id, stringName){
  ns <- NS(id)
  fluidRow(
    column(12,
      plotOutput(stringName)
    )
  )
}

testPlot <- function(data, xAxis, yAxis){
  output$test <- renderPlot({
    ggplot(data(), aes_string(x=xAxis(), y=yAxis())) + geom_bar(stat = "identity")
  })
}

這段代碼最終會出現以下錯誤:

模塊中的錯誤(childScope $ input,childScope $ output,childScope等):未使用的參數(childScope $ input,childScope $ output,childScope)

我該如何進行這項工作?

出現該錯誤的原因是, inputoutputsession是模塊服務器部分的前三個參數,這一點很重要。 因此,您需要更改:

testPlot <- function(data, xAxis, yAxis){
  output$test <- renderPlot({
    ggplot(data(), aes_string(x=xAxis(), y=yAxis())) + geom_bar(stat = "identity")
  })
}

變成:

testPlot <- function(input, output, session, data, xAxis, yAxis){
  output$test <- renderPlot({
    ggplot(data(), aes_string(x=xAxis(), y=yAxis())) + geom_bar(stat = "identity")
  })
}

僅此一項更改,您的代碼現在就可以正常運行了。 但是,什么也不會出現。 那是因為您忘記了使用模塊的另一個關鍵組件,該組件將所有輸入/輸出ID封裝在ns()函數中。 所以改變:

column(12,
       plotOutput(stringName)
)

變成:

column(12,
       plotOutput(ns(stringName))
)

現在,您應該會看到情節出現沒有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM