Alternative to ifelse with radiobutton in R Shiny Dashboard - r

I am creating a dashboard that displays a graph based on the selected demographic combination. Since there are 3 main categories, one method that works is to use ifelse. cars is just a random plot used to demonstrate.
cars <- c(1,3,6,4,9)
header <- dashboardHeader(title = "Financial Independence")
sidebar <- dashboardSidebar(
sidebarMenu(
id = "tabs",
menuItem("Financial Independence Status", tabName = "finstat"),
menuItem("Expense Type", tabName = "expt")
),
actionButton('switchtab', 'Switch tab')
)
body <- dashboardBody(
tabItems(
tabItem(tabName = "finstat",
h2("Amount of Financial Help Received From Parents in the Last 12 Months")
, "Created by Daniel Haw Rong Chen & Althea Laverne Muth"
, fluidRow(
column(width = 2, height = 3, wellPanel(radioButtons("finstat_all", "All Demographics",
c("Yes", "No")))),
column(width = 2, height = 3, wellPanel(radioButtons("finstat_sex", "Sex",
c("Male", "Female")))),
column(width = 3, height = 3, wellPanel(radioButtons("finstat_educ", "Education Level",
c("College Graduate+", "Some College"
, "H.S. Graduate or Less")))),
column(width = 3, height = 3, wellPanel(radioButtons("finstat_reth", "Race/Ethnicity",
c("White non-Hispanic", "Black non-Hispanic"
, "Hispanic", "Other")))),
),
mainPanel(
plotOutput("plot1")
)
),
tabItem(tabName = "expt",
h2("Types of Expense Financial Help Is Spent On")
, "Created by Daniel Haw Rong Chen & Althea Laverne Muth"
, fluidRow(
column(width = 2, style = "height:200px", wellPanel(radioButtons("expt_all", "All Demographics",
c("Yes", "No")))),
column(width = 2, style = "height:200px", wellPanel(radioButtons("expt_sex", "Sex",
c("Male", "Female")))),
column(width = 3, style = "height:200px", wellPanel(radioButtons("expt_educ", "Education Level",
c("College Graduate+", "Some College"
, "H.S. Graduate or Less")))),
column(width = 3, style = "height:200px", wellPanel(radioButtons("expt_reth", "Race/Ethnicity",
c("White non-Hispanic", "Black non-Hispanic"
, "Hispanic", "Other")))),
),
mainPanel(
plotOutput("plot2")
)
)
)
)
ui <- dashboardPage(
header,
sidebar,
body
)
server <- function(input, output, session) {
observeEvent(input$switchtab, {
newtab <- switch(input$tabs,
"finstat" = "expt",
"expt" = "finstat"
)
updateTabItems(session, "tabs", newtab)
})
tabItems(
tabItem(tabName = "finstat",
output$plot1 <- renderPlot({
if (input$finstat_sex == "Male") {
if (input$finstat_educ == "College Graduate+") {
if (input$finstat_reth == "White non-Hispanic") {
plot(cars)
}
}
}
})
),
tabItem(tabName = "expt",
output$plot2 <- renderPlot({
if(input$expt_all == "Yes"){
ggplot(data = help_type_all, aes(x = type, y = perc, fill = ans, label = round(perc, 4)*100)) +
geom_col(position = "stack") +
geom_text(size = 3, color = "white", position = position_stack(vjust = 0.5)) +
labs(x = "Expense Type", y = "Proportion"
, title = "Type of Expense the Financial Help Is Related To") +
scale_x_discrete(labels=c("Education"
, "Household"
, "Med"
, "Rent or\nMortgage")) +
guides(fill = guide_legend(title = "Response")) + # to rename legend
scale_fill_manual(labels = c("Related", "Unrelated"), values = c("deepskyblue3", "darksalmon")) +
scale_y_continuous(labels = scales::percent) +
theme(legend.title = element_text(size = 10, face = "bold")
, legend.title.align = 0.5
, plot.title = element_text(face = "bold", hjust = 0.5)
, axis.title.x = element_text(face = "bold", hjust = 0.5)
, axis.title.y = element_text(face = "bold", hjust = 0.5))
}
if (input$expt_sex == "Male"
& input$expt_educ == "College Graduate+"
& input$expt_reth == "White non-Hispanic") {
ggplot(data = help_type_m_c_w, aes(x = type, y = perc, fill = ans, label = round(perc, 4)*100)) +
geom_col(position = "stack") +
geom_text(size = 3, color = "white", position = position_stack(vjust = 0.5)) +
labs(x = "Expense Type", y = "Proportion"
, title = "Type of Expense the Financial Help Is Related To") +
scale_x_discrete(labels=c("Education"
, "Household"
, "Med"
, "Rent or\nMortgage")) +
guides(fill = guide_legend(title = "Response")) + # to rename legend
scale_fill_manual(labels = c("Related", "Unrelated"), values = c("deepskyblue3", "darksalmon")) +
scale_y_continuous(labels = scales::percent) +
theme(legend.title = element_text(size = 10, face = "bold")
, legend.title.align = 0.5
, plot.title = element_text(face = "bold", hjust = 0.5)
, axis.title.x = element_text(face = "bold", hjust = 0.5)
, axis.title.y = element_text(face = "bold", hjust = 0.5))
}
})
)
)
}
shinyApp(ui, server)
The problem, however, is that I need to create a graph for each possible combination, so using ifelse will create a code that is overwhelmingly large.
Are there good alternatives to ifelse in this case?
The specific section that I need help with is the following:
tabItem(tabName = "finstat",
output$plot1 <- renderPlot({
if (input$finstat_sex == "Male") {
if (input$finstat_educ == "College Graduate+") {
if (input$finstat_reth == "White non-Hispanic") {
plot(cars)
}
}
}
})
)
How the dashboard look like for more context

Related

Select current plot and download to file

How can I save the current plot that is displayed on the mainPanel? I am having trouble pointing the correct graphic to the download Handler. This is what I have:
library(shiny)
library(ggplot2)
library(tidyverse)
library(shinythemes)
library(plotly)
library(scales)
library(shinyWidgets)
library(shinydashboard)
library(shinyjs)
# Define input choices
type <- c("first", "second")
#Data for lambda
table <- structure(list(year = 1991:2010, lambda = c(0.68854, 0.75545,
1.63359, 1.22282, 1.70744, 1.09692, 0.51159, 1.3904, 1.09132,
0.59846, 0.43055, 0.80135, 0.69027, 0.65646, 0.95485, 1.04818,
0.67859, 1.00461, 1.16665, 1.28203)), row.names = c(NA, -20L), class = "data.frame")
ui <- fluidPage(
useShinyjs(), # to initialise shinyjs
navbarPage("Test",
windowTitle = "A Test",
sidebarPanel(
h3(""),
#Dropdown to select the desired kind of graphic
selectInput(inputId = "graphtype",
label = "Graphic",
choices = type,
selected = "first"),
disabled( #start as disabled
checkboxInput("Fixed","Fixed Y axes", FALSE))),
downloadButton('downloadPlot', 'Download Plot'),
#Graphic Area mainPanel. Graphic on top and table right below it
mainPanel(plotOutput("plot"),
dataTableOutput("mytable"))
))
###################################################################################################
server<- function (input, output, session) {
session$onSessionEnded(function() {
stopApp()
})
#Plot data
output$plot <- renderPlot({
xlabels <- 1991:2011
switch(input$graphtype,
"first" = {
disable("Fixed")
print(ggplot(table,aes(year,lambda)) + geom_line(size=1.5,colour="blue") + geom_point(colour="orange",size=4) +
scale_x_continuous("",breaks = xlabels) +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
labs(x="",y="test",title= paste0("Population growth rate of Fish ")))
},
{
enable("Fixed")
if(input$Fixed == FALSE){
"second" <- print(ggplot(table,aes(year,lambda)) + geom_line(size=1.5,colour="red") + geom_point(colour="green",size=4) +
scale_x_continuous("",breaks = xlabels) +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
labs(x="",y="fish test",title= paste0("Population growth")))
}
else{
"second" <- print(ggplot(table,aes(year,lambda)) + geom_line(size=1.5,colour="yellow") + geom_point(colour="green",size=4) +
scale_x_continuous("",breaks = xlabels) +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
labs(x="",y="fish test",title= paste0("Population growth")))
}
}
)
output$downloadPlot <- downloadHandler(
filename = "plot.png" ,
content = function(file) {
ggsave(plot(), filename = file)
})
})
}
shinyApp(ui = ui, server = server)
One option would be to move your plotting code to a reactive. This way you could print your plot inside renderPlot but also pass the plot to the ggsave inside the downloadHandler. Additionally I cleaned up the code to switch between the plots a little bit.
Note: I moved the download button to the sidebar because otherwise it would not work. Also, I made the code more minimal by removing all the unnecessary packages and code.
library(shiny)
library(ggplot2)
# Define input choices
type <- c("first", "second")
# Data for lambda
table <- structure(list(year = 1991:2010, lambda = c(
0.68854, 0.75545,
1.63359, 1.22282, 1.70744, 1.09692, 0.51159, 1.3904, 1.09132,
0.59846, 0.43055, 0.80135, 0.69027, 0.65646, 0.95485, 1.04818,
0.67859, 1.00461, 1.16665, 1.28203
)), row.names = c(NA, -20L), class = "data.frame")
ui <- fluidPage(
sidebarPanel(
h3(""),
# Dropdown to select the desired kind of graphic
selectInput(
inputId = "graphtype",
label = "Graphic",
choices = type,
selected = "first"
),
checkboxInput("Fixed", "Fixed Y axes", FALSE),
downloadButton("downloadPlot", "Download Plot")
),
# Graphic Area mainPanel. Graphic on top and table right below it
mainPanel(
plotOutput("plot"),
dataTableOutput("mytable")
)
)
###################################################################################################
server <- function(input, output, session) {
session$onSessionEnded(function() {
stopApp()
})
# Plot data
create_plot <- reactive({
xlabels <- 1991:2011
if (input$graphtype == "first") {
ggplot(table, aes(year, lambda)) +
geom_line(size = 1.5, colour = "blue") +
geom_point(colour = "orange", size = 4) +
scale_x_continuous("", breaks = xlabels) +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
labs(x = "", y = "test", title = paste0("Population growth rate of Fish "))
} else {
if (!input$Fixed) {
ggplot(table, aes(year, lambda)) +
geom_line(size = 1.5, colour = "red") +
geom_point(colour = "green", size = 4) +
scale_x_continuous("", breaks = xlabels) +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
labs(x = "", y = "fish test", title = paste0("Population growth"))
} else {
ggplot(table, aes(year, lambda)) +
geom_line(size = 1.5, colour = "yellow") +
geom_point(colour = "green", size = 4) +
scale_x_continuous("", breaks = xlabels) +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
labs(x = "", y = "fish test", title = paste0("Population growth"))
}
}
})
output$plot <- renderPlot({
create_plot()
})
output$downloadPlot <- downloadHandler(
filename = function() "plot.png",
content = function(file) {
ggsave(create_plot(), filename = file)
}
)
}
shinyApp(ui = ui, server = server)

Conditional withSpinner

I am trying to use a conditional withSpinner such that when users select Ohio, both sexes and the year of 2010, I want the spinner to come up. Otherwise, I do not want the spinner to be shown. Please see this image for more information. In other words, I want to disable the spinner when, for example, the year is changed to 2015. Is there any way to do this.
.
Here is the simplified version of my codes:
UI
ui <- fluidPage(
navbarPage(
collapsible = T,
fluid = T,
selected = "Population Projections",
windowTitle = "Scripps Interactive Data Center",
"",
tabPanel(("Population Projections"),
# tags$hr(), #add a line between above command and the below one
tags$h5 (
strong("Current and Projected Population by County, Age Group, and Sex, 2010-2050"),
align = 'left'
),
br(),
#a line break
sidebarLayout(
sidebarPanel(
#"sidebar panel"),
helpText("Please select your county of interest"),
selectInput(
inputId = "county",
label = "Select County:",
selected = "Ohio",
selectize = FALSE,
multiple = FALSE,
choices = sort(unique(population$County))
),
radioButtons(
inputId = "sex",
label = strong("Select Sex:"),
selected = "Both Sexes",
choices = sort(unique(population$Sex))
),
sliderInput(
inputId = "years",
label = "Year",
min = 2010,
max = 2050,
value = 2010,
step = 5,
sep = "",
pre = "",
animate = animationOptions(
interval = 1000,
loop = F,
playButton = tags$button("Play", style =
"background-color: #B61E2E ; color:white; margin-top: 10px; border:solid"),
pauseButton = tags$button("Pause", style =
"background-color: #B61E2E !important; color:white; margin-top: 10px; border:solid")
),
round = T,
width = "150%",
ticks = T
),
# ### Download Button
downloadButton("downloadData", "Download Data"),
br(),
br()
# downloadButton("downloadPlot_1", "Download Bar Graph"),
# br(),
# br(),
# downloadButton("downloadPlot_2", "Download Pyramid"),
# br(),
# br()
# the number of visitors
# h5(textOutput("counter"))
),
######################
mainPanel(
tabsetPanel(
type = "tabs",
tabPanel(
"Plot",
plotOutput("bar") %>% withSpinner (color="#B61E2E"),
br(),
br(),
br(),
#a line break
(column (12, align="center", tableOutput("table")))
),
tabPanel(
"Pyramid",
plotOutput("pyramid", height=600)
#a line break
),
tabPanel("Data", tableOutput("data"))
)
)
Server
server <- function(input, output) {
bardata <- reactive ({
out <- population %>%
filter (County %in% input$county,
Year %in% input$years,
Sex %in% input$sex)
return(out)
})
blue.bold.14.text <- element_text(face = "bold", color = "black", size = 14)
blue.bold.10.text <- element_text(face = "bold", color = "black", size = 10)
blue.bold.12.text <- element_text(face = "bold", color = "black", size = 12)
bardataPlot <- reactive({
ggplot(bardata(), aes(x = Age_Group, y = Population)) + geom_bar(stat =
"identity",
position = "stack",
fill = "#B61E2E") +
geom_text(
aes(label = Percentage),
vjust = 1,
colour = "white",
position = position_dodge(width=0.9),
fontface = "bold",
size=5,
angle = 90,
hjust = 1
) +
labs(
x = "Age Groups",
y = "Population Size",
caption = (""),
face = "bold"
) +
theme_bw() + scale_y_continuous(labels = scales::comma) +
theme(plot.title = element_text(
hjust = 0.5,
size = 15,
colour = "Black",
face = "bold"
),axis.text=(blue.bold.12.text), axis.title=blue.bold.14.text, axis.text.x = element_text(angle = -75, vjust = 0, hjust=0)) +
ggtitle(
paste0(
input$sex,
" ",
"Population Size by 5-Year Age Groups in ",
input$county,
", ",
input$years
)
)
})
output$bar <- renderPlot ({
bardataPlot()
})
As your non-minimal example isn't working (parenthesis missing?) I made a new one showing a way to display a spinner conditionally:
library(shiny)
library(shinycssloaders)
ui <- fluidPage(
checkboxInput("toggle", "toggle"),
conditionalPanel(condition = "input.toggle", withSpinner(uiOutput("spinnerDummyID1"), type = 6))
)
server <- function(input, output, session) {}
shinyApp(ui, server)

Whitespace in rendertable output on ShinyDashboard

I am creating a table using renderTable and a plot (plotly) to be placed in ShinyDashboard. There is a whitespace that surrounds the table data that I am trying to get rid off. However, there is no whitespace around the plot.
How do I remove the whitespace that surround the table i have added to my shiny dashboard.
How do I align the header of the table "Recruitment" to the center?
I know there are some HTML solutions, but I am not familiar with those codes and will be glad if someone can explain.
Here are my codes:
Server codes
output$recruit_stats <- renderTable(recruit_stats, bordered = TRUE, colnames = TRUE)
output$Recruitment_bar_plot <- renderPlotly({
Recruitment_bar<-Recruitment_bar[(Recruitment_bar$hospital!="H"),];
R01 <- ggplot()+
geom_bar(data=Recruitment_bar,aes(x=hospital,y=count),stat = "identity", fill="navyblue")+
ylim(0,1200) +
geom_text(data=Recruitment_bar,aes(x=hospital,y=count*1.05,label=paste(count)),size=2.5, vjust=-1.0) +
theme(panel.background = element_blank(),
axis.text = element_text(size = 7),
axis.title = element_text(size=7),
axis.line = element_line(colour = "black", size = 0.5, linetype = "solid"),
plot.title = element_text(size=8, face="bold", hjust=0.5),
legend.position = "none", legend.text = element_text(size=6)) +
labs(fill="") + guides(fill = guide_legend(reverse=TRUE))+
ylab("No. Recruited") + ggtitle("No. of Patients Recruited (Jan 2017 to June 2018)")
ggplotly(R01, tooltip=c("count"));
})
UI codes
Recruitment<-tabItem(
tabName = "Recruitment",
fluidRow(
box(
box(title = "Recruitment",
status = "primary",
solidHeader = TRUE,column(12,tableOutput("recruit_stats"), align="c"),
width=8,
collapsed=TRUE)
),
box(
plotlyOutput("Recruitment_bar_plot", height = 400),
width=5,
status = "primary",
solidHeader = TRUE
)
)
)
I would drop boxes and try grid by columns. For table have a look at DT tutorials.
library(shiny)
library(shinydashboard)
dat5 <- c(rep("Female", 3376), rep("Male", 2180))
app <- shinyApp(
ui <- shinyUI(
dashboardPage(dashboardHeader(title = "PSM"),
dashboardSidebar(),
dashboardBody(
tabItem(
tabName = "Recruitment",
fluidRow(
column(width=6,
DT::dataTableOutput("recruit_stats")),
column(width=6,
plotOutput("pie_chart", height = 400))
)
)
))
),
server <- shinyServer(function(input,output){
output$pie_chart <- renderPlot({
df <- table(dat5)
cols <- rainbow(length(df))
barplot(df, col = cols)
})
output$recruit_stats <- DT::renderDataTable({
DT::datatable(as.data.frame(dat5), options = list(paging=TRUE, searching= TRUE ))
})
})
)
runApp(app)

shiny checkboxGroupInput ggplots as list

Could anyone suggest me the way to extract shiny checkboxgroupoinput options of different ggplots such as geom_bar(), geom_line() as a list. I tried the following simplified code, it prints only the last plot: Thanks for your help.
library(shiny)
library(ggplot2)
library(easyGgplot2)
patient <- cbind.data.frame(seq(1:14),matrix(sample(1:100, 84), ncol=6))
colnames(patient) <- c('DAYS', 'PHYSICAL_ACTIVITY', 'SMOKING','ALCOHOL_INTAKE', 'HYDRATION', 'SLEEP', 'Total_score')
ui <- fluidPage(
titlePanel("Data Plot"),
sidebarLayout(
sidebarPanel(
fluidRow(column(6,
checkboxGroupInput("checkGroup",
("Parameters"),
list("PHYSICAL ACTIVITY" = 1,
"SLEEP" = 2,
"ALCOHOL INTAKE" = 3,
"SELECT ALL" = 4
)))
),
fluidRow(column(10, actionButton("goButton", label = "Analysis Report"))
)
), #Sidebarpanel
mainPanel(
plotOutput("plot1", height='800px')
)#Mainpanel
) #Sidebar layout
)#fluidpage
server <- function(input, output) {
output$plot1 <- renderPlot({
input$goButton
p1 <- reactive({
if(!(1 %in% input$checkGroup)) return(NULL)
ggplot(data=patient, aes(x=DAYS, y=PHYSICAL_ACTIVITY))+geom_bar(stat="identity", aes(fill=PHYSICAL_ACTIVITY<=median(PHYSICAL_ACTIVITY)), show.legend=F)+scale_fill_manual(values = c('steelblue', 'red') )+labs(title = 'PHYSICAL ACTIVITY (STEPS)', x = NULL, y = NULL)+theme_minimal()
})
# Second plot
p2 <- reactive ({
if(!(2 %in% input$checkGroup )) return(NULL)
p2 <- ggplot(data=patient, aes(x=DAYS,y=SLEEP))+geom_line(colour='black', size=1)+geom_point(size=3, aes(colour=cut(SLEEP,c(-Inf,summary(SLEEP)[[2]],summary(SLEEP)[[5]],Inf))), show.legend=F)+scale_color_manual(values = c("red", "orange","green"))+labs(title = 'SLEEP (hrs)', x = NULL, y = NULL) +theme_minimal()
})
ptlist <- list(p1(),p2())
ggplot2.multiplot(ptlist, cols=1)
})
}
shinyApp(ui, server)
Example with reading csv.
library(shiny)
library(ggplot2)
library(easyGgplot2)
patient <- cbind.data.frame(
seq(1:14),
matrix(
sample(1:100, 84),
ncol = 6
)
)
colnames(patient) <- c(
'DAYS',
'PHYSICAL_ACTIVITY',
'SMOKING',
'ALCOHOL_INTAKE',
'HYDRATION',
'SLEEP',
'Total_score'
)
write.csv(patient, file="patient.csv")
ui <- fluidPage(
titlePanel("Data Plot"),
sidebarLayout(
sidebarPanel(
fluidRow(
column(6,
checkboxGroupInput(
"checkGroup",
"Parameters",
list(
"PHYSICAL ACTIVITY",
"SLEEP"),
selected = "PHYSICAL ACTIVITY")
)
),
fluidRow(
fileInput("file1", "Choose Data sheet",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv"))
)
),
mainPanel(
plotOutput("plots")
)
)
)
server <- function(input, output) {
patient <- reactive({
req(input$file1)
read.csv(input$file1$datapath,
header = T
)
})
plot_one <- function(patient.data) {
ggplot(patient.data, aes(x = DAYS, y = PHYSICAL_ACTIVITY)) +
geom_bar(
stat = "identity",
aes(fill = PHYSICAL_ACTIVITY <= median(PHYSICAL_ACTIVITY)),
show.legend = F) +
scale_fill_manual(
values = c('steelblue', 'red')) +
labs(title = 'PHYSICAL ACTIVITY (STEPS)',
x = NULL,
y = NULL) +
theme_minimal()
}
plot_two <- function(patient.data){
ggplot(patient.data, aes(x = DAYS, y = SLEEP)) +
geom_line(colour = 'black', size = 1) +
geom_point(size = 3,
aes(colour = cut(SLEEP,
c(-Inf,
summary(SLEEP)[[2]],
summary(SLEEP)[[5]],
Inf)
)
),
show.legend = F) +
scale_color_manual(values = c("red", "orange", "green")) +
labs(title = 'SLEEP (hrs)',
x = NULL,
y = NULL) +
theme_minimal()
}
output$plots <- renderPlot({
list.of.plots <- list(
`PHYSICAL ACTIVITY` = plot_one(patient()),
`SLEEP` = plot_two(patient())
)
do.call(ggplot2.multiplot, c(list.of.plots[input$checkGroup], cols=1))
})
}
shinyApp(ui, server)
It will work if replace ggplot2.multiplot(ptlist, cols=1) by do.call(ggplot2.multiplot, c(ptlist, cols=1))
But may be to do this with ggplot function in reactive is not a good way to achieve your goal.
You could to try something like this
library(shiny)
library(ggplot2)
library(easyGgplot2)
patient <- cbind.data.frame(
seq(1:14),
matrix(
sample(1:100, 84),
ncol = 6
)
)
colnames(patient) <- c(
'DAYS',
'PHYSICAL_ACTIVITY',
'SMOKING',
'ALCOHOL_INTAKE',
'HYDRATION',
'SLEEP',
'Total_score'
)
ui <- fluidPage(
titlePanel("Data Plot"),
sidebarLayout(
sidebarPanel(
fluidRow(
column(6,
checkboxGroupInput(
"checkGroup",
"Parameters",
list(
"PHYSICAL ACTIVITY",
"SLEEP"),
selected = "PHYSICAL ACTIVITY")
)
)
),
mainPanel(
plotOutput("plots")
)
)
)
server <- function(input, output) {
plot_one <- ggplot(data = patient, aes(x = DAYS, y = PHYSICAL_ACTIVITY)) +
geom_bar(
stat = "identity",
aes(fill = PHYSICAL_ACTIVITY <= median(PHYSICAL_ACTIVITY)),
show.legend = F) +
scale_fill_manual(
values = c('steelblue', 'red')) +
labs(title = 'PHYSICAL ACTIVITY (STEPS)',
x = NULL,
y = NULL) +
theme_minimal()
plot_two <- ggplot(data = patient, aes(x = DAYS, y = SLEEP)) +
geom_line(colour = 'black', size = 1) +
geom_point(size = 3,
aes(colour = cut(SLEEP,
c(-Inf,
summary(SLEEP)[[2]],
summary(SLEEP)[[5]],
Inf)
)
),
show.legend = F) +
scale_color_manual(values = c("red", "orange", "green")) +
labs(title = 'SLEEP (hrs)',
x = NULL,
y = NULL) +
theme_minimal()
list.of.plots <- list(
`PHYSICAL ACTIVITY` = plot_one,
`SLEEP` = plot_two
)
output$plots <- renderPlot(
do.call(ggplot2.multiplot, c(list.of.plots[input$checkGroup], cols=1))
)
}
shinyApp(ui, server)
library(shiny)
library(ggplot2)
library(easyGgplot2)
patient <- cbind.data.frame(
seq(1:14),
matrix(
sample(1:100, 84),
ncol = 6
)
)
colnames(patient) <- c(
'DAYS',
'PHYSICAL_ACTIVITY',
'SMOKING',
'ALCOHOL_INTAKE',
'HYDRATION',
'SLEEP',
'Total_score'
)
write.csv(patient, file="patient.csv")
ui <- fluidPage(
titlePanel("Data Plot"),
sidebarLayout(
sidebarPanel(
fluidRow(
column(6,
checkboxGroupInput(
"checkGroup",
"Parameters",
list(
"PHYSICAL ACTIVITY",
"SLEEP"),
selected = "PHYSICAL ACTIVITY")
)
),
fluidRow(
fileInput("file1", "Choose Data sheet",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv"))
)
),
mainPanel(
plotOutput("plots")
)
)
)
server <- function(input, output) {
patient <- reactive({
req(input$file1)
read.csv(input$file1$datapath,
header = T
)
})
plot_one <- ggplot(data = patient(), aes(x = DAYS, y = PHYSICAL_ACTIVITY)) +
geom_bar(
stat = "identity",
aes(fill = PHYSICAL_ACTIVITY <= median(PHYSICAL_ACTIVITY)),
show.legend = F) +
scale_fill_manual(
values = c('steelblue', 'red')) +
labs(title = 'PHYSICAL ACTIVITY (STEPS)',
x = NULL,
y = NULL) +
theme_minimal()
plot_two <- ggplot(data = patient(), aes(x = DAYS, y = SLEEP)) +
geom_line(colour = 'black', size = 1) +
geom_point(size = 3,
aes(colour = cut(SLEEP,
c(-Inf,
summary(SLEEP)[[2]],
summary(SLEEP)[[5]],
Inf)
)
),
show.legend = F) +
scale_color_manual(values = c("red", "orange", "green")) +
labs(title = 'SLEEP (hrs)',
x = NULL,
y = NULL) +
theme_minimal()
list.of.plots <- list(
`PHYSICAL ACTIVITY` = plot_one,
`SLEEP` = plot_two
)
output$plots <- renderPlot(
do.call(ggplot2.multiplot, c(list.of.plots[input$checkGroup], cols=1))
)
}
shinyApp(ui, server)

R Shiny Creating Reactive (Single) Plot from Multiple User Inputs

The goal is to create an interactive (Single) plot that the user can select
the year of interest, the status of the member, and the service of interest
and each will select the correct data point. Each x,y coordinate is the
mean satisfaction and mean importance respectively. I have it working with
just the services (plot colm), but Id like to be able to have the user
have more selection. My attempt for multiple inputs is plotOutput("test")..
Any ideas how to get this code working?? THANK YOU!!
UI:
importance <- c(4.25, 3.08)
satisfaction <- c(3.90, 3.18)
dfGap <- data.frame(importance, satisfaction)
imp.A <- c("3.2","2.5","3.3","4.5","4","3.7")
sat.b <- c("2.2", "3.7","5","1.2","2.6","3")
yr.c <- c("2016","2016","2017","2016", "2016","2017")
status.d <- c("Student", "Not","Student", "Not","Student","Student")
service.e <- c("Huddle", "Web", "Test", "Web","Other","Huddle")
dfTest <- data.frame(imp.A,sat.b,yr.c,status.d, service.e)
colDepend = ("darkred")
range <- c("2016"=1,"2017"=2)
choices <- c("Web" = 1,"Huddle" = 2, "Other" = 3, "Test" = 4)
role <- c("Student" = 1, "Not" = 2)
library(shiny)
library(shinydashboard)
library(ggplot2)
ui <- dashboardPage(
dashboardHeader(title="Membership Satisfaction"),
dashboardSidebar(
sidebarMenu(
menuItem("Value Dashboard", tabName = "dashboard", icon =
icon("dashboard")),
menuItem("Services Dashboard", tabName = "service", icon =
icon("dashboard")),
menuItem("Demographics Dashboard", tabName = "demos", icon =
icon("dashboard"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "service",
sidebarPanel(checkboxGroupInput("vars","Select variables to
plot", choices = choices)),
fluidPage(
plotOutput("colm"),
br(),
br(),
br(),
br(),
br(),
br(),
br(),
br(),
h6(strong("Gap Analysis: Plot points calculated as mean
importance and mean satisfaction."),
style = "font-family:'calibri"),
br(),
br(),
h6(strong("Strength: These are the primary strengths. We are
meeting highly important services with high satisfaction."),
style = "font-family:'calibri"),
h6(strong("Potential Advantages: Member satisfaction is being
met, however these services may not be as important for brand
equity."),
style = "font-family:'calibri"),
h6(strong("Secondary Opportunitites: These services are not
crucial (not highly important) and should not be a primary
focus."),
style = "font-family:'calibri"),
h6(strong("Target Issues: Targeting efforts here can improve
membership. These are services that are highly important
however are not meeting needs of members."),
style = "font-family:'calibri")
)),
tabItem(tabName = "demos",
sidebarPanel(
checkboxGroupInput("inpt","Select variables to plot", choices =
choices),
checkboxGroupInput("role",
"Select Primary Role of Interest",
choices = role),
checkboxGroupInput("yrs",
"Select year(S) of Interest",
choices = range)),
fluidPage(
plotOutput("test")
)
))
)
)
Server:
server <- function(input,output){
output$matrixValue<- renderTable({
matrixValue
},include.rownames=TRUE)
output$matrixRENEW<- renderTable({
matrixRENEW
},include.rownames=TRUE)
output$value_BP <- renderPlot({
barplot(matrixValue, beside = T,
legend.text=rownames(matrixValue),
args.legend=list(x="topleft"),
main = titleValue,col=cols)})
output$renew_BP<- renderPlot({
barplot(matrixRENEW, beside = T,
legend.text=rownames(matrixRENEW),
args.legend=list(x="topleft"),
main = titleRENEW,col=cols)})
output$colm <- (renderPlot({
ggplot(dfGap[input$vars,], aes(satisfaction,importance))+
theme(text=element_text(size=12))+
geom_point(colour =input$vars, shape = 17, size=5 )+
labs(x = "Mean Satisfaction", y = "Mean Importance") +
xlim(0,5) + ylim(0,5)+
geom_vline(xintercept=2.5) + geom_hline(yintercept = 2.5)+
annotate("text", x = 4.8, y = 5,
label = "Strengths",
color = "chartreuse4",
style = "font-family:'calibri",
size =6.5,
fontface =2)+
annotate("text", x = .3, y = 5,
label = "Target Issues",
color = "firebrick4",
style = "font-family:'calibri",
size =6.5,
fontface =2)+
annotate("text", x = .78, y = 0,
label = "Secondary Opportunities",
color = "dodgerblue3",
style = "font-family:'calibri",
size =6.5,
fontface =2)+
annotate("text", x = 4.4, y = 0,
label = "Potential Advantages",
color = "grey10",
style = "font-family:'calibri",
size =6.5,
fontface =2)
}))
output$test <- renderPlot({
ggplot(dfTest[service.e[service.e==input$inpt,],], aes(imp.A,sat.b))+
theme(text=element_text(size=12))+
geom_point(colour ="green", shape = 17, size=5 )+
labs(x = "Mean Satisfaction", y = "Mean Importance") +
xlim(0,5) + ylim(0,5)+
geom_vline(xintercept=2.5) + geom_hline(yintercept = 2.5)+
annotate("text", x = 4.8, y = 5,
label = "Strengths",
color = "chartreuse4",
style = "font-family:'calibri",
size =6.5,
fontface =2)+
annotate("text", x = .3, y = 5,
label = "Target Issues",
color = "firebrick4",
style = "font-family:'calibri",
size =6.5,
fontface =2)+
annotate("text", x = .78, y = 0,
label = "Secondary Opportunities",
color = "dodgerblue3",
style = "font-family:'calibri",
size =6.5,
fontface =2)+
annotate("text", x = 4.4, y = 0,
label = "Potential Advantages",
color = "grey10",
style = "font-family:'calibri",
size =6.5,
fontface =2)})
}
shinyApp (ui = ui, server = server)
The service tab is working how I'd like the demos tab to work, I'm just struggling with getting the different user inputs to map to a plot in a similar way. Any help is GREATLY appreciated!!

Resources