Shiny app - hide/show text comment under the plot after clicking checkbox - r

I want to build an app with the checkbox asking whether to show additional text comments under the figures.
I would like to display set of plots with or without an explanation - this shall be left to the user, whether they need more info or not.
Here are some dummy comments:
#info for box1:
"This is the red histogram"
#info for box2:
"This is the blue histogram"
Here is a dummy app:
library(shiny)
library(shinydashboard)
data <- rnorm(10000, mean=8, sd=1.3)
variable <- "This is the blue histogram"
shinyApp(
ui = dashboardPage(
skin = "black",
dashboardHeader(
title = "Example app",
titleWidth = 300
),
dashboardSidebar(
checkboxInput("show_comment",
label = "Show comment?",
value = FALSE)
),
dashboardBody(
box(title = "First histogram",
status= "warning",
plotOutput("plot1", height=300)
),
box(title = "Second histogram",
status= "warning",
plotOutput("plot2", height=300),
hidden(
div(id='text_div',
verbatimTextOutput("text")))
)
)
),
server = function(input, output) {
output$plot1 <- renderPlot({
hist(data, breaks=40, col="red", xlim=c(2,14), ylim=c(0,800))
})
output$plot2 <- renderPlot({
hist(data, breaks=20, col="blue", xlim=c(2,34), ylim=c(0,1000))
})
observeEvent(input$show_comment, {
toggle('text_div')
output$text <- renderText({ paste0(variable)})
})
}
)
The above code does not work properly - it displays comment no matter if the checkbox is clicked or not. I'd like to make it work, therefore seek for advice here.
I was trying to do it on my own using following hints, to no avail:
How to use shiny actionButton to show & hide text output?
This syntax is too complex for me as I am a beginner with shiny, so I was not able to troubleshoot my problem with hints from this thread:
Show and hide text in modularized shiny app based on actionButton() and shinyJS()
I also tried ths:
Hide/show outputs Shiny R
And here is the attempt of using above hint:
library(shiny)
library(shinydashboard)
data <- rnorm(10000, mean=8, sd=1.3)
variable <- "This is the blue histogram"
shinyApp(
ui = dashboardPage(
skin = "black",
dashboardHeader(
title = "Example app",
titleWidth = 300
),
dashboardSidebar(
checkboxInput("show_comment",
label = "Show comment?",
value = FALSE)
),
dashboardBody(
box(title = "First histogram",
status= "warning",
plotOutput("plot1", height=300)
),
box(title = "Second histogram",
status= "warning",
plotOutput("plot2", height=300),
renderText("text", span(variable))
)
)
),
server = function(input, output) {
output$plot1 <- renderPlot({
hist(data, breaks=40, col="red", xlim=c(2,14), ylim=c(0,800))
})
output$plot2 <- renderPlot({
hist(data, breaks=20, col="blue", xlim=c(2,34), ylim=c(0,1000))
})
observeEvent(input$show_comment, {
# every time the button is pressed, alternate between hiding and showing the plot
toggle("text")
})
}
)
I want to put the comments inside the same box, along with the plot - this is why I am trying to enclose it with the box command. However, if it is impossible - I would be glad of any other solution.

First time I use shinyjs so there might be a better approach. But as I understand it from the docs you first have to add useShinyjs() in your UI code
in order for all other shinyjs functions to work.
Second, there is no need to wrap the div for your comment in hidden(). Third, instead of using observeEvent I followed the example in ?toggle and use an observe where I add the state of your checkbox as the condition to trigger the toggle.
library(shiny)
library(shinydashboard)
library(shinyjs)
data <- rnorm(10000, mean = 8, sd = 1.3)
variable <- "This is the blue histogram"
shinyApp(
ui = dashboardPage(
skin = "black",
dashboardHeader(
title = "Example app",
titleWidth = 300
),
dashboardSidebar(
checkboxInput("show_comment",
label = "Show comment?",
value = FALSE
)
),
dashboardBody(
box(
title = "First histogram",
status = "warning",
plotOutput("plot1", height = 300)
),
box(
title = "Second histogram",
status = "warning",
plotOutput("plot2", height = 300),
div(id = "text_div",
verbatimTextOutput("text")
)
)
),
useShinyjs()
),
server = function(input, output) {
output$plot1 <- renderPlot({
hist(data, breaks = 40, col = "red", xlim = c(2, 14), ylim = c(0, 800))
})
output$plot2 <- renderPlot({
hist(data, breaks = 20, col = "blue", xlim = c(2, 34), ylim = c(0, 1000))
})
observe({
toggle(id = "text_div", condition = input$show_comment)
output$text <- renderText({
paste0(variable)
})
})
}
)
#>
#> Listening on http://127.0.0.1:7437

Related

Cannot specify input dataset in shiny dashboard

I am trying to make a shiny dashboard. I have two datasets, and based upon the selection of the datasets figures will be generate in the tab panels. However, by default only the last dataset that has been loaded/read is selected and I cannot select the first dataset. Even though I have made it default selection.
Below is my code.
library(shinydashboard)
library(uwot)
library(DESeq2)
library(gridExtra)
library(tidyverse)
library(RColorBrewer)
library(DESeq2)
library(pheatmap)
library(DEGreport)
library(vsn)
library(RColorBrewer)
library("genefilter")
library(org.Hs.eg.db)
library(dplyr)
library(tidyverse)
library(fgsea)
library(clusterProfiler)
library(ggplot2)
set_1<-load("C:/Users/abn/Documents/Shiny/DashBoardTutorial/TeData2.RData")
set_2<-load("C:/Users/abn/Documents/Shiny/DashBoardTutorial/TeData1.RData")
data_list = list(set_1=set_1,set_2=set_2)
ui <- dashboardPage(
dashboardHeader(title = "Data Visualizer", titleWidth = 300),
dashboardSidebar(
width = 300,
sidebarMenu(
menuItem("Datasets", icon = icon("cog"),
selectInput("Datasets", "Datasets:", choices = list("sample1" = "set_1", "sample2" = "set_2"),
selected = "set_1")),
menuItem("Quality Control", tabName = "widgets", icon = icon("th")),
menuItem("Differential Genes", tabName = "widgets2", icon = icon("th")),
menuItem("Downstream", tabName = "widgets3", icon = icon("th"))
)
),
## Body content
dashboardBody(
tabItems(
# First tab content
# Second tab content
tabItem(tabName="widgets",
h2("widgets"),
plotOutput("widgets"),
),
tabItem(tabName = "widgets2",
h2("Widgets2 tab content"),
),
tabItem(tabName = "widgets3",
h2("Widgets3 tab content"),
plotOutput("widgets3"),
)
)
)
)
server <- function(input, output) {
datasetInput <- reactive({
df <- data_list[[input$Datasets]]
})
output$widgets <- renderPlot({
datasetInput()
par(mfrow=c(1,2))
boxplot(counts(dds, normalized=F), outline=F, col=dds$condition, medcol = "white", cex.axis=0.6, main="Without Normalization")
boxplot(counts(dds, normalized=T), outline=F, col=dds$condition, medcol = "white", cex.axis=0.6, main="Normalized")
})
}
shinyApp(ui, server)
I am sure that I am missing a small trick, could anyone of you shiny masters help me out.
Or may be there is a better way to do the above procedure.
Many thanks in advance
Assuming you have access to both datasets, you plot them both and display the selection. Try this
data_list = list(set_1=mtcars,set_2=iris)
ui <- dashboardPage(
dashboardHeader(title = "Data Visualizer", titleWidth = 300),
dashboardSidebar(
width = 300,
sidebarMenu(
menuItem("Datasets", icon = icon("cog"),
selectInput("Datasets", "Datasets:", choices = list("sample1" = "set_1", "sample2" = "set_2"),
selected = "set_1")),
menuItem("Quality Control", tabName = "widgets", icon = icon("th")),
menuItem("Differential Genes", tabName = "widgets2", icon = icon("th")),
menuItem("Downstream", tabName = "widgets3", icon = icon("th"))
)
),
## Body content
dashboardBody(
tabItems(
# First tab content
# Second tab content
tabItem(tabName="widgets",
h2("widgets"),
#plotOutput("widgets"),
uiOutput("widgets")
),
tabItem(tabName = "widgets2",
h2("Widgets2 tab content"),
),
tabItem(tabName = "widgets3",
h2("Widgets3 tab content"),
plotOutput("widgets3"),
)
)
)
)
server <- function(input, output) {
# datasetInput <- reactive({
# df <- data_list[[input$Datasets]]
# })
#
# output$widgets <- renderPlot({
# datasetInput()
# par(mfrow=c(1,2))
#
# boxplot(counts(dds, normalized=F), outline=F, col=dds$condition, medcol = "white", cex.axis=0.6, main="Without Normalization")
# boxplot(counts(dds, normalized=T), outline=F, col=dds$condition, medcol = "white", cex.axis=0.6, main="Normalized")
#
# })
output$plot1 <- renderPlot({
boxplot(mpg ~ cyl , data=mtcars)
})
output$plot2 <- renderPlot({
boxplot(Sepal.Length ~ Species , data=iris)
})
output$widgets <- renderUI({
if (input$Datasets=="set_1") { plotOutput("plot1")
}else plotOutput("plot2")
})
}
shinyApp(ui, server)

Save reactive value of selectInput when switching tabs

I have a selectInput menu that comes up when I have a certain tab open in my window. I use the same selectInput (inside renderMenu) for multiple tabs. I would like to figure out how to save the value chosen on one tab so it will be the chosen value when switching tabs. Here, for example, if I choose the mtcars plots tab and select 'blue', and then switch to mtcars plots 2, I would like the selected color to be kept at 'blue' rather than switching back to the first option of red.
Yes, I am aware that I am not currently doing anything with the colors, I will add that usage in later.
library(shiny)
library(shinythemes)
library(shinydashboard)
library(tidyverse)
options(warn=-1)
data(iris)
data(mtcars)
# Define UI for application that draws a histogram
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(
sidebarMenu(id = "menume",
sidebarMenuOutput("colormenu"),
menuItem("MTCARS", tabName = "mt", icon = icon("user-tie")),
selectInput("mtvar", "Choose a variable", choices = colnames(mtcars)),
menuItem("IRIS", icon = icon("envelope-open-text"), tabName = "ir"),
selectInput("irvar", "Choose a variable", choices = colnames(iris))
)
),
dashboardBody(
tabItems(
tabItem("mt", uiOutput("mttabs")),
tabItem("ir", uiOutput("irtabs"))
)
)
)
# ui <- secure_app(ui, enable_admin = TRUE)
# Begin Server ----------------------------------------------
server <- function(input, output, session) {
output$colormenu = renderMenu({
req((input$menume=="mt"& input$mtcarstabsall%in%c(2,3))||
(input$menume=="ir"& input$iristabsall%in%c(5,6)))
selectInput("colorme", "Choose a color", c("red", "yellow", "green", "blue", "black"))
})
output$mttabs = renderUI({
output$mtcarsplot1=renderPlot({
ggplot(mtcars, aes_string(x = input$mtvar)) + stat_bin(nbins = 10)
})
output$mtcarsplot2=renderPlot({
ggplot(mtcars, aes_string(x = input$mtvar)) + geom_density()
})
output$mtcarstable1=renderTable({
tabme= head(mtcars, 5)
tabme
})
tabsetPanel(id = "mtcarstabsall",
tabPanel(id = "mttable","MTcars tables",value=1,
fluidRow(box(title = "Table 1", tableOutput("mtcarstable1")))
),
tabPanel(id = "mtplots","mtcars plots",value=2,
fluidRow(box(title = "Plot1", plotOutput("mtcarsplot1"))
)),
tabPanel(id = "mtplots2","mtcars plots 2",value=3,
fluidRow(box(title = "Plot1", plotOutput("mtcarsplot2")))))
})
output$irtabs = renderUI({
output$irisplot1=renderPlot({
ggplot(iris, aes_string(x = input$irvar)) + stat_bin(nbins = 10)
})
output$irisplot2=renderPlot({
ggplot(iris, aes_string(x = input$irvar)) + geom_density()
})
output$iristable1=renderTable({
tabme = head(iris, 5)
tabme
})
tabsetPanel(id = "iristabsall",
tabPanel(id = "mttable","iris tables",value=4,
fluidRow(box(title = "Table 1", tableOutput("iristable1")))
),
tabPanel(id = "irisplots","iris plots",value=5,
fluidRow(box(title = "Plot1", plotOutput("irisplot1"))
)),
tabPanel(id = "irisplots2","iris plots 2",value=6,
fluidRow(box(title = "Plot2", plotOutput("irisplot2"))
)))
})
}
shinyApp(ui, server)
The issue is that the color menu is re-rendering every time you switch tabs and so it resets the selected value. For something like this what you want to do instead is just show/hide the element rather than add/remove it (which is what you're currently doing with req()).
You could use a conditionalPanel in your menu or use the shinyjs package with something like the below (remembering to add shinyjs::useShinyjs() to your ui, to show/hide the color menu:
output$colormenu = renderMenu({
# Remove the req
selectInput("colorme", "Choose a color", c("red", "yellow", "green", "blue", "black"))
})
observe({
# Show/hide menu based on condition using shinyjs::toggle
show_menu_condition <- (input$menume=="mt"& input$mtcarstabsall%in%c(2,3)) || (input$menume=="ir"& input$iristabsall%in%c(5,6))
shinyjs::toggle("colormenu",
condition = show_menu_condition)
})

Shiny WebApp and UI: add style and dropdown menu in the header

I'm just starting using R and Shiny App and I'm a bit confused about how to achieve what I'm trying to do. I want to change the UI of my Shiny App. As a C# developer, I work with HTML/CSS, AdminLTE and so on. I can't find a proper documentation how to change the UI in a Shiny App.
What I want to achieve in the UI is something like the following image:
First, I removed the sidebar. Now, my problem is to box the UI. In the header, I want to add a dropdown menu with few options. Then, I want in the middle of the page to have a panel with 2 column: in the first column first row I desire to see the graph generate by R, then same text around it to explain the graph.
On top of that, I want to change the style for example of tabs or buttons.
After 2 days of work, I wrote this code but it is very far from what I want to achieve.
library(shiny)
library(shinydashboard)
# Define UI for application that draws a histogram
ui <- navbarPage(
"Test",
tabPanel(
"Introduction",
titlePanel(
div(
windowTitle = "Test window"
)
),
div(class = "my-class",
h3("LAI287 basal insulin study"),
p("Lorem ipsum dolor sit amet..."),
p("Lorem ipsum dolor sit amet..."),
actionButton(
inputId = "btnStart",
label = "Start analysis",
className = "btn-primary"
)
)
),
tabPanel(
"Attribute specification"
),
tabPanel(
dropdownMenu(type = "notifications",
notificationItem(
text = "5 new users today",
icon("users")
),
notificationItem(
text = "12 items delivered",
icon("truck"),
status = "success"
),
notificationItem(
text = "Server load at 86%",
icon = icon("exclamation-triangle"),
status = "warning"
)
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
# Run the application
shinyApp(ui = ui, server = server)
The result of this code is in the following screenshot. The only dropdown I found was for messages or notifications.
I know AdminLTE quite well but I don't understand how to write the code for Shiny App. Do you have any idea or suggestion how I can implement this UI? Is there any good tutorial I can read?
Update
I found some documentation on RStudio Shiny dashboard. First, I don't understand the difference between dashboardPage and navbarPage. Can I add a navbarPage to a dashboardPage?
From the documentation, I added this code:
box(
title = "Histogram", status = "primary", solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plot3", height = 250)
),
box(
title = "Inputs", status = "warning", solidHeader = TRUE,
"Box content here", br(), "More box content",
sliderInput("slider", "Slider input:", 1, 100, 50),
textInput("text", "Text input:")
)
and I expect something like
but my result is like that (thanks Jan for the menu)
I saw on the other page of the documentation that it is possible to add
dashboardPage(skin = "blue")
but in my case I don't have a dashboardPage.
Are you aware of the navbarMenu function? You can add menu items to the navbarPage with it:
navbarPage("App Title",
tabPanel("Plot"),
navbarMenu("More",
tabPanel("Summary"),
"----",
"Section header",
tabPanel("Table")
)
)
Layouting can be done with fluid layouts, e.g.
fluidRow(
column(width = 4,
"4"
),
column(width = 3, offset = 2,
"3 offset 2"
)
See the layout guide for the necessary details.
If you are familiar with AdminLTE then I strongly recommend using bs4Dash. It is a very robust package that allows for the use of boxes and other features that are regularly a part of AdminLTE (including Bootstrap 4). But the core of the language is still Shiny, so you may need to work through a few basic examples before attempting anything with greater complexity.
You can change colors, font-sizes, etc. in bs4Dash by following the instructions on this page.
For a demo of what is possible, see here.
I've provided a very basic example at the bottom of this answer.
Otherwise adding a dropdown navigation in bs4Dash is a bit tricky, and will require a combination of Javascript, CSS, and HTML. Luckily, you can modify all of these things.
Good luck!
library(shiny)
library(bs4Dash)
ui <- dashboardPage(
header = dashboardHeader(
leftUi = tagList(
dropdownMenu(
badgeStatus = "info",
type = "notifications",
notificationItem(
inputId = "notice1",
text = "Put text here!",
status = "danger"
)
),
dropdownMenu(
badgeStatus = "info",
type = "tasks",
taskItem(
inputId = "notice2",
text = "My progress",
color = "orange",
value = 10
)
)
)
),
dashboardSidebar(disable = T),
body = dashboardBody(
fluidRow(
column(width = 8,
box(width = NULL, title = "Old Faithful Geyser Data",
collapsible = F,
wellPanel( sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)),
plotOutput("distPlot")
),
box(width = NULL, title = NULL, collapsible = F,
fluidRow(
column(width = 5,
tags$img(src = "https://i.stack.imgur.com/EslMF.png", width = '100%')
),
column(width = 7,
tags$h4("Card Title"),
tags$p("Some text here")
)
)
)
),
column(width = 4,
box(width = NULL, title = "Header", status = "info", collapsible = F),
box(width = NULL, title = "Header", status = "success", collapsible = F),
box(width = NULL, title = "Header", status = "secondary", collapsible = F)
)
)
),
controlbar = dashboardControlbar(
collapsed = FALSE,
div(class = "p-3", skinSelector()),
pinned = TRUE
)
)
server <- function(input, output) {
output$distPlot <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
shinyApp(ui = ui, server = server)

Shiny: Dynamic height adjustment of plot

Problem: In belows Shiny app the user can add information presented in valueboxes depending on the select input. If the user selects all possible choices then the UI looks as in the screenshot.
Question: Is it possible that the plot (which is in the same row as the valueboxes) adjusts in height (so the bottom of the plot is aligned with the bottom of the last valuebox)?
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(
selectizeInput(
inputId = "select",
label = "Select country:",
choices = c("CH", "JP", "GER", "AT", "CA", "HK"),
multiple = TRUE)
),
dashboardBody(
fluidRow(column(2, uiOutput("ui1")),
column(10, plotOutput("some_plot"))))#,
# column(4, uiOutput("ui2")),
# column(4, uiOutput("ui3")))
)
server <- function(input, output) {
output$ui1 <- renderUI({
req(input$select)
lapply(seq_along(input$select), function(i) {
fluidRow(
valueBox(value = input$select[i],
subtitle = "Box 1",
width = 12)
)
})
})
output$some_plot <- renderPlot(
plot(iris)
)
}
shinyApp(ui = ui, server = server)
You can adjust the height in the renderPlot. I have set the minimum to 3 value box height. So, it starts increasing the height after you add 3 value boxes. You can modify it, as necessary. Try the code below.
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(
selectizeInput(
inputId = "select",
label = "Select country:",
choices = c("CH", "JP", "GER", "AT", "CA", "HK"),
multiple = TRUE)
),
dashboardBody(
fluidRow(column(2, uiOutput("ui1")),
column(10, plotOutput("some_plot"))))#,
# column(4, uiOutput("ui2")),
# column(4, uiOutput("ui3")))
)
server <- function(input, output) {
plotht <- reactiveVal(360)
observe({
req(input$select)
nvbox <- length(input$select)
if (nvbox > 3) {
plotheight <- 360 + (nvbox-3)*120
}else plotheight <- 360
plotht(plotheight)
})
output$ui1 <- renderUI({
req(input$select)
lapply(seq_along(input$select), function(i) {
fluidRow(
valueBox(value = input$select[i],
subtitle = "Box 1",
width = 12)
)
})
})
observe({
output$some_plot <- renderPlot({
plot(iris)
}, height=plotht())
})
}
shinyApp(ui = ui, server = server)
Here's my attempt, based on this answer. This uses the window size listeners to dynamically adjust the size of a plot (possible by using inline = TRUE in the plotOutput call). The width of the outer container is fixed, so can be referenced directly, but the height is dynamic, so my workaround is to use the window height and subtract 50 pixels. This seems to work as long as there is a single plot element, and the sidebar hasn't been adjusted to be on top of the plot, rather than beside it.
The window resizes are debounced to only resize after there's been no change for half a second, so that the server isn't taxed too much in redraw calls. The code also doesn't plot anything if the dimensions are not yet determined, so that there's no initial plot flicker.
library(shiny)
ui <- fluidPage(
## Add a listener for the window height and plot container width
tags$head(tags$script('
var winDims = [0, 0];
var plotElt = document;
$(document).on("shiny:connected", function(e) {
plotElt = document.getElementById("plotContainer");
winDims[0] = plotElt.clientWidth;
winDims[1] = window.innerHeight;
Shiny.onInputChange("winDims", winDims);
});
$(window).resize(function(e) {
winDims[0] = plotElt.clientWidth;
winDims[1] = window.innerHeight;
Shiny.onInputChange("winDims", winDims);
});
')),
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30),
sliderInput("height", label="Height",
min=100, max=900, value = 600)
),
mainPanel(
tags$div(id="plotContainer", ## Add outer container to make JS constant
## Use an "inline" plot, so that width and height can be set server-side
plotOutput("distPlot", inline = TRUE))
)
)
)
server <- function(input, output) {
## reduce the amount of redraws on window resize
winDims_d <- reactive(input$winDims) %>% debounce(500)
## fetch the changed window dimensions
getWinX <- function(){
print(input$winDims);
if(is.null(winDims_d())) { 400 } else {
return(winDims_d()[1])
}
}
getWinY <- function(){
if(is.null(winDims_d())) { 600 } else {
return(winDims_d()[2] - 50)
}
}
output$distPlot <- renderPlot({
if(is.null(winDims_d())){
## Don't plot anything if we don't yet know the size
return(NULL);
}
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
}, width = getWinX, height=getWinY)
}
shinyApp(ui = ui, server = server)

Specifying different number of output plots/tables (Shiny app)

I want to give the user option to select which plots/tables he/she wants to see at the end of an analysis.
All the plots are produced from one dataset and include time series plots, boxplots, histograms etc.
The questions I stumbled upon are
Do I use one or multiple plotOutput("Plot",....) element? So far I have been arranging plots in one figure so one plotOutput was sufficient
Do I use the predefined height, as in plotOutput("Plot",height = "1800px")?
If the number of figures varies this creates empty space, I would like to avoid it.
How to add Tables with results?
Any comments would be very appreciated, Mac
You can wrap you plots in conditionalPanel's to deselect them.
For this you will need 1. multiple plotOutput's.
2. When everything is wrapped in a fluidRow there won't be any empty space.
3. See the following example and: http://shiny.rstudio.com/reference/shiny/0.14/tableOutput.html
library(shiny)
library(shinydashboard)
library(shinyWidgets)
ui <- dashboardPage(
dashboardHeader(title = "Plot selection"),
dashboardSidebar(
materialSwitch(inputId="switch1", label = "Show plot 1", value = TRUE, status = "primary"),
materialSwitch(inputId="switch2", label = "Show plot 2", value = TRUE, status = "primary"),
materialSwitch(inputId="switch3", label = "Show plot 3", value = TRUE, status = "primary"),
materialSwitch(inputId="switch4", label = "Show plot 4", value = TRUE, status = "primary")
),
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(
conditionalPanel(condition = "input.switch1", box(plotOutput("plot1", height = 250))),
conditionalPanel(condition = "input.switch2", box(plotOutput("plot2", height = 250))),
conditionalPanel(condition = "input.switch3", box(plotOutput("plot3", height = 250))),
conditionalPanel(condition = "input.switch4", box(plotOutput("plot4", height = 250))),
column(12,
dataTableOutput('table')
)
)
)
)
server <- function(input, output) {
df <- data.frame(col1 = rnorm(500), col2 = rnorm(500), col3 = rnorm(500), col4 = rnorm(500))
output$plot1 <- renderPlot({
plot(df$col1, col="red", main="Plot 1")
})
output$plot2 <- renderPlot({
plot(df$col2, col="green", main="Plot 2")
})
output$plot3 <- renderPlot({
plot(df$col3, col="blue", main="Plot 3")
})
output$plot4 <- renderPlot({
plot(df$col4, col="black", main="Plot 4")
})
output$table <- renderDataTable(df)
}
shinyApp(ui, server)
Edit ----------------------------------------
Here is a pure shiny version:
library(shiny)
ui <- fluidPage(
titlePanel("Plot selection"),
sidebarLayout(
sidebarPanel(width = 2,
checkboxInput(inputId="switch1", label = "Show plot 1", value = TRUE),
checkboxInput(inputId="switch2", label = "Show plot 2", value = TRUE),
checkboxInput(inputId="switch3", label = "Show plot 3", value = TRUE),
checkboxInput(inputId="switch4", label = "Show plot 4", value = TRUE)
),
mainPanel(
fluidRow(
conditionalPanel(condition = "input.switch1", plotOutput("plot1", height = 250)),
conditionalPanel(condition = "input.switch2", plotOutput("plot2", height = 250)),
conditionalPanel(condition = "input.switch3", plotOutput("plot3", height = 250)),
conditionalPanel(condition = "input.switch4", plotOutput("plot4", height = 250)),
column(12,
dataTableOutput('table')
)
)
)
)
)
server <- function(input, output) {
df <- data.frame(col1 = rnorm(500), col2 = rnorm(500), col3 = rnorm(500), col4 = rnorm(500))
output$plot1 <- renderPlot({
plot(df$col1, col="red", main="Plot 1")
})
output$plot2 <- renderPlot({
plot(df$col2, col="green", main="Plot 2")
})
output$plot3 <- renderPlot({
plot(df$col3, col="blue", main="Plot 3")
})
output$plot4 <- renderPlot({
plot(df$col4, col="black", main="Plot 4")
})
output$table <- renderDataTable(df)
}
# shinyApp(ui, server)
shinyApp(ui = ui, server = server)
For further information see:
https://rstudio.github.io/shinydashboard/get_started.html
https://dreamrs.github.io/shinyWidgets/reference/materialSwitch.html

Resources