Is it possible to use the Shiny conditionalPanel in a horizontal orientation?

Currently, I am working on crafting a shiny app that utilizes sidebarLayout() and the goal is to display either one or two plots side by side in the mainPanel(). The decision on how many plots to show is based on an input value set in the sidebarPanel().

In scenarios where only one plot is required, I aim for that plot to occupy 100% of the horizontal space within the mainPanel. Conversely, if both plots need to be displayed, each should take up 50% of the mainPanel space.

Specifically, I also want the contents of each column to utilize all available horizontal space within their respective columns.

I have experimented with various approaches:

  1. Utilizing a fluidRow() with a column and a conditionalPanel()

    • This method encountered challenges as fluidRow() expects width parameters from each element, while conditionalPanel() seemed incompatible.
  2. Employing conditionalPanel() in the right part of a splitLayout()

    • However, this approach merely hides the right-hand side and does not enable the left plot to expand to occupy all the mainPanel() space.
  3. Integrating a conditionalPanel() inside a right div with display: table-cell property

    • Unfortunately, this yielded similar outcomes as mentioned above.
library(ggplot2)
library(shiny)

ui <- fluidPage(
  tags$head(
    tags$style("
               #my_container {
                 display: table;
                 width: 100%;
               }

               .col {
                 display: table-cell;
               }

               #col_left {
                 background-color: #ffa;
               }

               #col_right {
                 background-color: #faf;
               }
               ")
  ), 

  sidebarPanel(
    checkboxInput("checkbox", 
                  "View Both", 
                  value = TRUE), 
    width = 2
  ), 

  mainPanel(
    div(id = "my_container", 
        div(id = "col_left", 
            class ="col", 
            plotOutput("plot_output_1")),
        div(id = "col_right", 
            class = "col", 
            conditionalPanel("input.checkbox == 1", 
                             plotOutput("plot_output_2")))
    ), 
    width = 10
  )
)

server <- shinyServer(function(input, output) {
  output$plot_output_1 <- renderPlot({
    ggplot(
      data.frame(x = runif(3), y = rnorm(3)), 
      aes(x = x, y = y)) + 
      geom_point()
  })

  output$plot_output_2 <- renderPlot({
    ggplot(
      data.frame(x = runif(3), y = rnorm(3)), 
      aes(x = x, y = y)) + 
      geom_point()
  })
})

shinyApp(ui, server)
  1. Another attempt involved incorporating JavaScript mechanisms to adjust the div widths.
    • While successful in hiding the right column and revealing the left column, the left plot did not automatically readjust to fill the new space despite being redrawn due to input dependency.
library(ggplot2)
library(shiny)

ui <- fluidPage(
  tags$head(
    tags$style("
               #my_container {
                 display: table;
                 width: 100%;
               }

               .my_col {
                 display: table-cell;
               }

               #col_left {
                 background-color: #ffa;
               }

               #col_right {
                 background-color: #faf;
               }
               "
    ), 

    tags$script("
      Shiny.addCustomMessageHandler('n_show.onchange', function(value) {
        var col_left = document.getElementById('col_left');
        var col_right = document.getElementById('col_right');

        if(value == 'one') {
          col_left.style.width = '100%';
          col_right.style.width = '0%';
        } else {
          col_left.style.width = '50%'; 
          col_right.style.width = '50%';
        }
      });
      "
    )
  ), 

  sidebarPanel(
    selectInput(inputId = "n_show", label = "Number of Plots", choices = c("one", "two"), selected = "two"), 
    width = 2
  ), 

  mainPanel(
    div(id = "my_container", 
        div(id = "col_left", 
            class = "my_col", 
            plotOutput("plot_output_1")),
        div(id = "col_right", 
            class = "my_col", 
            conditionalPanel("input.n_show == 'two'", 
                             plotOutput("plot_output_2")))
    ), 
    width = 10
  )
)

server <- shinyServer(function(input, output, session) {
  output$plot_output_1 <- renderPlot({
    input$n_show

    ggplot(
      data.frame(x = runif(3), y = rnorm(3)), 
      aes(x = x, y = y)) + 
      geom_point()
  })

  output$plot_output_2 <- renderPlot({
    input$n_show

    ggplot(
      data.frame(x = runif(3), y = rnorm(3)), 
      aes(x = x, y = y)) + 
      geom_point()
  })

  observeEvent(input$checkbox, {
    session$sendCustomMessage("n_show.onchange", input$n_show)
  })
})

shinyApp(ui, server)

My conviction is that this task is not overly complex, but my familiarity with CSS seems insufficient - particularly in the realm of shiny application development.

Answer №1

Implementing a solution using renderUI:

library(ggplot2)
library(shiny)

ui <- fluidPage(
  tags$head(
    tags$style("
               #col_left {
                 background-color: #ffa;
               }
               #col_right {
                 background-color: #faf;
               }
               ")
    ), 

  sidebarPanel(
    checkboxInput("checkbox", 
                  "Display Both", 
                  value = TRUE), 
    width = 2
  ), 

  mainPanel(
    uiOutput("plots"), 
    width = 10
  )
    )

server <- shinyServer(function(input, output) {

  output$plot_output_1 <- renderPlot({
    ggplot(
      data.frame(x = runif(3), y = rnorm(3)), 
      aes(x = x, y = y)) + 
      geom_point(size = 6)
  })

  output$plot_output_2 <- renderPlot({
    ggplot(
      data.frame(x = runif(3), y = rnorm(3)), 
      aes(x = x, y = y)) + 
      geom_point(size = 6)
  })

  output$plots <- renderUI({
    if(input$checkbox){
      fluidRow(
        column(6, div(id="col_left", plotOutput("plot_output_1"))),
        column(6, div(id="col_right", plotOutput("plot_output_2")))
      )
    }else{
      fluidRow(
        column(12, div(id="col_left", plotOutput("plot_output_1")))
      )
    }
  })
})

shinyApp(ui, server)

https://i.sstatic.net/CnJJG.gif

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Chrome is having trouble displaying Roboto font correctly

I have been experiencing an issue with the rendering of the Roboto font on a client's website. When I view the site in Chrome (version 43.0.2357.65 m), all the different weights of Roboto appear to look the same. For example, here is a comparison: On ...

Ranger package encounters errors when using fit_resamples function

Utilize crossfold resampling and fit a random forest from the ranger package. The fitting process works fine without resampling, but encounters an error when attempting to perform a resample fit as shown below: Consider the dataset df df<-structure(li ...

What is the best way to compare two files and extract the necessary information using if statements in R?

As someone new to writing R scripts independently, I have a specific task in mind: Data Frame 1 (DF1): Chr Start End Region chr6 3324 3360 Region1 chr4 2445 2455 Region2 chr1 1034 1090 Region4 Data Frame 2 (Reference DF) ...

Display or conceal div elements using JavaScript

Is there a way to hide certain divs when clicking on a specific div box? Clicking on the box will trigger the hiding of some application divs. See the first image below: When the boxes are hidden, the other divs will readjust in place of the current divs ...

Tips for adding global styles to the html and body elements in SCSS without utilizing the @import rule

Many experts recommend avoiding the use of @import in SASS due to its deprecation in the future. However, when it comes to applying global styling in SCSS, what alternative methods can be used? ...

Preserving the slope of every iteration within a loop in R

Need assistance with extracting and saving slopes for each iteration to plot as a histogram in R. The goal is to modify the existing loop to achieve this outcome. Please share any insights or suggestions on how to accomplish this task. Thank you! plot(t ...

Gradient Heatmap2 with an extra touch of solid color shading

The heatmap I'm currently using generates a color gradient ranging from 0.7 to 1.3 through the heatmap.2 function: heatmap.2(lifespan.matrix, col=bluered, breaks=c(seq(0.7,1.3,0.01)), Rowv = FALSE, Colv = FALSE, trace="none", main="Lifespan") When l ...

Is it possible to modify the color of a division row using an onchange event in JQuery?

I am facing a requirement to dynamically change the color of rows based on the dropdown onchange value. The rows are structured in divisions, which were previously tables. There are two main divisions with rows that need to be updated based on dropdown sel ...

Step-by-step guide on aligning a div of unknown height in the center of a div with a set

Struggling to center product images vertically within a fixed height box? Here's the code I've been working with: <div class="main-pic"> <ul> <li><img src="images/extra/laptop.jpg"></li> <li><img ...

What are the best strategies for creating documentation for R reference classes?

What is the best way to document R reference classes? I searched through "Writing R extensions" on CRAN, but could only find guidelines for S3 and S4 objects. Is there anyone who can share an example of documentation for an R ref class and its correspondi ...

Can you explain the significance of the "style.css?ver=1" tag?

Recently, I noticed that certain websites incorporate a CSS tag such as style.css?ver=1. Can you explain the significance of this? What exactly is the purpose of adding ?ver=1 to the CSS tag? Could you provide instructions on how to implement this in cod ...

What causes my elements to move to the left when the screen size decreases with bootstrap?

If you want a better understanding of the situation, looking at images might be helpful. Here is how it typically appears: https://i.sstatic.net/mBZDp.jpg And this is how it appears on smaller screens: https://i.sstatic.net/8CuIs.jpg For smaller scree ...

Tips for minimizing the arrow size in the infowindow on a Google Maps interface

As a newcomer to customizing Google Maps, I am looking to decrease the size of the arrow in the infowindow and position it in the bottom left corner for a better appearance. I am struggling to figure out how to adjust the height and width of the arrow and ...

Configuration of flexbox for cordova on a Samsung Galaxy Tab running on Android version 4.1.2

I am having trouble using flexbox css to design a cordova app on a Galaxy Tab running Android 4.1.2 Here is the CSS code I am currently using: .container { /*display: flex; display: -webkit-box;*/ display: -webkit-flex; /*justify-content: ...

Tips for utilizing a variable within a variable containing HTML code

Is it possible to incorporate variables in a JavaScript function that includes HTML code? Let's consider the following example: function SetCFonts() { var Color = $('#CColor').val(); var Font = $('#CFont').val(); var S ...

Achieving overlapping div layouts with CSS styling

Displayed above are 4 different divs: red, green, and blue. I am seeking to have the blue div positioned directly below the green div, which contains the text "JACKSON". Additionally, I do not want the green div to expand beyond its content, nor do I want ...

The combination of loading and scrolling JavaScript code is not functioning properly on the website

I created an HTML webpage that includes some JavaScript code to enhance the user experience. However, I encountered an issue when trying to incorporate a load JavaScript function alongside the scroll JavaScript function on my page. The load script is posi ...

Working with Ext JS: Dynamically adjusting panel size when the browser window is resized

I am facing an issue with a side panel in Ext.js. Everything is working fine until I resize the browser, at which point some components of the panel get cut off. https://i.sstatic.net/eaEGI.png Is there a way to make the panel resize automatically when t ...

Adjusting the spacing between rows in Bootstrap 5

Having trouble with the spacing in my latest markup update. Here's what I have: <div class="row"> <div class="col-md-12"> <div class="form-group"> <label class="control-la ...

What are the steps to create a reliable menu?

Looking to add a fixed menu to my website that stays at the top even when scrolling down the page. For an example, check out iplex.co.in for a demonstration. ...