В моем mod_page_charts
на выходе есть две диаграммы TypeA_Chart
TypeB_Chart
,
В моем mod_page_ui
добавлен фильтр для диаграмм, где я пытаюсь фильтровать диаграммы, где выходные данные в tabPanel
для plotlyOutput
должны отображать диаграмму на основе выбранного типа диаграммы.
Как мне отобразить пользовательский интерфейс, чтобы диаграмма менялась в зависимости от выбора pickerInput
?
mod_page_ui <- function(id) {
ns <- NS(id)
tabItem(
tabName = "chart_page",
fluidPage(
fluidRow(
column(12, ),
fluidRow(column(12, tabsetPanel(
tabPanel("Value Chart " , fluidRow(
column(
2,
align = "center",
h3("Filter Chart"),
pickerInput(
inputId = ns("selectType"),
label = "Select Type to View",
choices = c("TypeA", "TypeB"),
selected = c("TypeA", "TypeB"),
),
uiOutput(ns("attributePicker"))
),
column(12, tabsetPanel(tabPanel(
"chart Panel ",
plotlyOutput(ns("TypeA_Chart"),
plotlyOutput(ns("TypeB_Chart")))
))))))))}
mod_page_charts <- function(input, output, session) {
ns <- session$ns
options(scipen = 100, digits = 4)
output$attributePicker <- renderUI({
if (input$selectType == "TypeA") {
pickerInput(
inputId = ns("selectedTypeA"),
label = "Select Category to View",
choices = c("Daily", "Weekly"),
selected = c("Daily", "Weekly"),
multiple = TRUE,
options = list(size = 5)
)
} else if (input$selectType == "TypeB") {
pickerInput(
inputId = ns("selectedTypeB"),
label = "Select Category to View",
choices = c("Daily", "Weekly"),
selected = c("Daily", "Weekly"),
multiple = TRUE,
options = list(size = 5)
)}})
output$TypeA_Chart <- renderPlotly({
plt <- generate_plot_typeA(
data = datatypeA,
attributeID = input$selectType,
x = `Dates`,
y = `Values`,
title = "Type-A Chart"
)
})
output$TypeB_Chart <- renderPlotly({
plt <- generate_plot_typeB(
data = datatypeB,
attributeID = input$selectType,
x = `Dates`,
y = `Values`,
title = "Type-B Chart"
)})
В вашем коде происходит много вещей, которые, я не уверен, намеренны или нет. Поскольку кажется, что вы хотите показать график только на основе условия, ConditionalPanel() может быть всем, что вам нужно.
Я урезал это до самых основ; Я пропустил использование модулей и удалил зависимость от shinydashboard
и shinyWidgets
, но должно работать так же. Для отображения панели не требуется ничего особенного от серверной составляющей. Приложение ниже просто показывает заголовок A is showing
и B is showing
на основе выбранных значений из selectInput()
.
library(shiny)
shinyApp(
fluidPage(
selectInput(
label = 'Select Type to View',
inputId = 'selectType',
choices = c('TypeA', 'TypeB'),
multiple = TRUE
),
conditionalPanel(
condition = 'input.selectType.includes("TypeA")',
h1('A is showing')
),
conditionalPanel(
condition = 'input.selectType.includes("TypeB")',
h1('B is showing')
)
),
server = function(input, output) {}
)
Если это удобнее, вы также можете рассмотреть возможность использования флажков. Ничего в состоянии внутри conditionalPanel
не должно измениться.
library(shiny)
shinyApp(
fluidPage(
checkboxGroupInput(
inputId = 'selectType',
label = 'Select Type to View',
choices = c('TypeA', 'TypeB')
),
conditionalPanel(
condition = 'input.selectType.includes("TypeA")',
h1('A is showing')
),
conditionalPanel(
condition = 'input.selectType.includes("TypeB")',
h1('B is showing')
)
),
server = function(input, output) {}
)
Отсюда просто замените h1()
своим сюжетом и визуализируйте его, не принимая во внимание какие-либо условия.
library(shiny)
library(plotly)
shinyApp(
fluidPage(
checkboxGroupInput(
inputId = 'selectType',
label = 'Select Type to View',
choices = c('TypeA', 'TypeB')
),
conditionalPanel(
condition = 'input.selectType.includes("TypeA")',
plotlyOutput('TypeA_Chart')
),
conditionalPanel(
condition = 'input.selectType.includes("TypeB")',
plotlyOutput('TypeB_Chart')
)
),
server = function(input, output) {
# sample data
data <- data.frame(x = 1:10, y = rnorm(10), group = sample(letters[1:3], 10, replace = TRUE))
output$TypeA_Chart <- renderPlotly(
# no conditions needed
plot_ly(data, x = ~x, y = ~y, type = 'scatter', mode = 'markers', color = ~group)
)
output$TypeB_Chart <- renderPlotly(
plot_ly(data, x = ~group, y = ~y, type = 'bar')
)
}
)
Если вы настаиваете на использовании модулей, обратите внимание, что в Shiny 1.5.0 появилась функция ModuleServer(), которая должна упростить часть создания серверной функции. Для conditionalPanel()
вам также необходимо передать саму функцию ns
.
library(shiny)
library(plotly)
chartModuleUI <- function(id) {
ns <- NS(id)
tagList(
checkboxGroupInput(
inputId = ns('selectType'),
label = 'Select Type to View',
choices = c('TypeA', 'TypeB')
),
conditionalPanel(
condition = 'input.selectType.includes("TypeA")',
plotlyOutput(ns('TypeA_Chart')),
ns = ns
),
conditionalPanel(
condition = 'input.selectType.includes("TypeB")',
plotlyOutput(ns('TypeB_Chart')),
ns = ns
)
)
}
chartModuleServer <- function(id) {
moduleServer(
id,
function(input, output, session) {
data <- data.frame(x = 1:10, y = rnorm(10), group = sample(letters[1:3], 10, replace = TRUE))
output$TypeA_Chart <- renderPlotly(
plot_ly(data, x = ~x, y = ~y, type = 'scatter', mode = 'markers', color = ~group)
)
output$TypeB_Chart <- renderPlotly(
plot_ly(data, x = ~group, y = ~y, type = 'bar')
)
}
)
}
shinyApp(
fluidPage(
chartModuleUI('chartModule')
),
server = function(input, output) {
chartModuleServer('chartModule')
}
)