r - 根据复选框在 plotOutput 和 plotlyOutput 之间切换
问题描述
我正在尝试构建一个 Shiny 应用程序,该应用程序仅plotly
在用户为交互式图形标记复选框时才加载。但是,到目前为止,我尝试过的最终都绘制了两个数字,而不管复选框值如何:
require('plotly')
require('shiny')
ui <- fluidPage(
tabsetPanel(
id = 'mainTab',
tabPanel(
'conditionally interactive tab',
checkboxInput(
inputId = 'interactive', label = 'Interactive figure', value = FALSE
),
conditionalPanel(
condition = 'input.interactive == TRUE',
plotlyOutput('interactivePlot')
),
conditionalPanel(
condition = 'input.interactive == FALSE',
plotOutput('staticPlot')
)
),
tabPanel('unrelated tab')
)
)
server <- function(input, output, session){
output$interactivePlot <- renderPlotly({
plot_ly(iris, x = ~Petal.Length, y = ~Sepal.Length)
})
output$staticPlot <- renderPlot({
plot(Sepal.Length ~ Petal.Length, iris)
})
}
shinyApp(ui = ui, server = server)
造成这种情况的原因是使用 plotly 时加载时间较长,以及在手持设备上使用 plotly 的不便(尝试使用对触摸有反应的绘图滚动很困难)。我不想为它们设置单独的选项卡,但我意识到如果没有其他方法可行,那可能是一种选择。
解决方案
你很亲密。条件condition
面板中的表达式是 JavaScript 表达式,也不是 R 表达式。在 JavaScript 中,他们使用true
/false
而不是TRUE
/ FALSE
。所以只要改变它,它就会起作用。
require('plotly')
require('shiny')
ui <- fluidPage(
tabsetPanel(
id = 'mainTab',
tabPanel(
'conditionally interactive tab',
checkboxInput(
inputId = 'interactive', label = 'Interactive figure', value = FALSE
),
conditionalPanel(
condition = 'input.interactive == true',
plotlyOutput('interactivePlot')
),
conditionalPanel(
condition = 'input.interactive == false',
plotOutput('staticPlot')
)
),
tabPanel('unrelated tab')
)
)
server <- function(input, output, session){
output$interactivePlot <- renderPlotly({
plot_ly(iris, x = ~Petal.Length, y = ~Sepal.Length)
})
output$staticPlot <- renderPlot({
plot(Sepal.Length ~ Petal.Length, iris)
})
}
shinyApp(ui = ui, server = server)
推荐阅读
- r - Matlab 到 R 的循环转换
- javascript - Javascript - :Slider On touch 未按预期工作
- javascript - 如何将 html id 更改为变量 Laravel
- listview - Xamarin Forms - 根据条件动态创建视图
- node.js - Azure DevOps CI/CD - Angular 项目 - nodeJS
- javascript - 在所有 siutes 之后如何运行 cy.task
- ios - 在路径数据模型或其他问题的情况下如何遵循干净的代码规则
- delphi - 如何从 TStyleBook 对象运行时更改样式书的样式资源属性
- javascript - 在 chrome 扩展的 background.js 中使用 npm run build 调用 JS 函数
- sql - DATEDIFF() 用于动态更改日期