r - 如何使用 R Shiny 中的单选按钮在同一图形上显示图?
问题描述
在这个闪亮的应用程序中,如果我们选择第二个单选按钮“在同一图上显示图”,我希望在同一图上显示两个图 提前谢谢您的帮助
library(shiny)
library(plotly)
ui <-fluidPage(
titlePanel("title panel"),
sidebarLayout(position = "left",
sidebarPanel(
radioButtons(inputId = "plot", label=' ', choices=c("display plots on separate figures", "display plots on the same figure"))
),
mainPanel(
plotlyOutput(outputId = "fbPlot1"),
plotlyOutput(outputId = "fbPlot2")
)
))
server <- function(input, output) {
output$fbPlot1 <- renderPlotly(
fig <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
)
output$fbPlot2 <- renderPlotly(
fig2 <- plot_ly(data = iris, x = ~Petal.Length, y = ~Sepal.Length,color ='blue')
)
}
shinyApp(ui = ui, server = server)
解决方案
通过使用 shinyjs 包,您可以根据事件隐藏/显示 UI 元素。
library(shiny)
library(plotly)
library(shinyjs)
ui <-fluidPage(
titlePanel("title panel"),
useShinyjs(),
sidebarLayout(position = "left",
sidebarPanel(
radioButtons(inputId = "plot", label=' ', choices=c("display plots on separate figures", "display plots on the same figure"))
),
mainPanel(
div(id = "plot1", plotlyOutput(outputId = "fbPlot1")),
div(id = "plot2", plotlyOutput(outputId = "fbPlot2")),
div(id = "plot3", plotlyOutput(outputId = "fbPlot3"))
)
))
server <- function(input, output) {
rv <- reactiveValues()
observe({
rv$fig1 <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
rv$fig2 <- plot_ly(data = iris, x = ~Petal.Length, y = ~Sepal.Length,color ='blue')
rv$fig3 <- subplot( rv$fig1, rv$fig2)
})
output$fbPlot1 <- renderPlotly({
rv$fig1
})
output$fbPlot2 <- renderPlotly({
rv$fig2
})
output$fbPlot3 <- renderPlotly({
rv$fig3
})
observeEvent(input$plot, {
req(input$plot)
print(input$plot)
if(input$plot == "display plots on separate figures"){
shinyjs::show("plot1")
shinyjs::show("plot2")
shinyjs::hide("plot3")
}
if(input$plot == "display plots on the same figure"){
shinyjs::hide("plot1")
shinyjs::hide("plot2")
shinyjs::show("plot3")
}
}, ignoreNULL = FALSE)
}
shinyApp(ui = ui, server = server)
推荐阅读
- azure-active-directory - AzureAD 方案和 OpendId aad 方案有什么区别?
- python - 在 python 上将此验证码中的图像转换为文本
- docusignapi - Docusign - 日期选项卡 - 格式化输入
- java - OpenCV JNI:Mat 的 Java/本机处理 - 删除被调用两次的可能性?
- cron - crontab 不发送邮件
- javascript - 我可以使用 ActionCable 刷新页面吗?
- sql - 如何将 unix 日期转换为雪花中的指定日期?
- wpf - 对于 UWP/WPF 项目的应用清单的可视资产部分,哪些是强制性的,哪些不是?
- sql - 使用 12 小时表示法格式化时间
- reactjs - 浏览多层 React 应用程序