Conditional withSpinner - r

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)

Related

R shiny tabbox plot overlapping

I have an shiny dashboard that contains multiple tabpanels, boxes that has datatable and plots.
With in the first panel tab, I have a datatable followed by two plot objects. I have put the plots into separate collapsible boxes. The issue I have is the plot is overlapping. I tried adjusting the heights to the box/tab box but I still get the overlapping plot.
I am looking at the 'Drug' tabpanel and the two plot objects are: plotlyOutput("drug_cleveland_plot") and plotOutput("drug_forest_plot").
I set the height of the box : height = 3000
Height of the plot that is overlapping: height = 1000
UI:
tabItem(
tabName = "comorbidities",
box(title = p("Medical History",
div(class = "qv_buttons",
actionButton("run_med_history", "Generate Report", icon = icon("refresh")),
shinyWidgets::radioGroupButtons("med_history_pop", label = NULL,
choices = list(#"Previously & Newly Diagnosed",
"Previously Diagnosed",
"Newly Diagnosed"),
selected = "Previously Diagnosed")
)
),
status = "success",
solidHeader = TRUE,
width = 12,
box(
width = 12 ,
height = 3000,
br(),
tabBox(
id = "med_history_tab",
tabPanel(
"Drug",
pickerInput(
inputId = "drug_class_selection",
label = "Drug Class:",
choices = c('ATC 1st', 'ATC 2nd', 'ATC 3rd', 'ATC 4th', 'ATC 5th', 'Ingredient'),
width = '50%'
),
DT::dataTableOutput("truven_med_history_drug_table", width = "850px"),
box(title = "Expected vs Observed Proportion Cleveland Plot",
collapsible = TRUE,collapsed = TRUE, plotlyOutput("drug_cleveland_plot"),width = "100%"),
box(title = "Expected vs Observed Proportion Odds Ratio",
collapsible = TRUE,collapsed = TRUE, plotOutput("drug_forest_plot"),width = "100%")),
tabPanel(
"Condition",
pickerInput(
inputId = "condition_hrc_selection",
label = "Condition Level:",
choices = c(0,1),
choicesOpt = list(subtext = c(" : Acual"," : 1 Level Higher")),
width = '50%'
),
#verbatimTextOutput('sel.cond'),
DT::dataTableOutput("truven_med_history_condition_table"),
actionButton('resetSelection', label = "Click to reset row selection"),
plotlyOutput('cond_cleveland_plot')
),
tabPanel(
"Procedure",
pickerInput(
inputId = "procedure_hrc_selection",
label = "Procedure Level:",
choices = c(0,1),
choicesOpt = list(subtext = c(" : Acual"," : 1 Level Higher")),
width = '50%'
),
#verbatimTextOutput('sel.proc'),
DT::dataTableOutput("truven_med_history_procedure_table")
),
tabPanel(
"Charlson Cormobidity",
DT::dataTableOutput("truven_med_history_cci_table"),
plotlyOutput("truv_cci_bar_plotly"),
br(),
plotlyOutput("cci_bar_plotly")
),
#plotOutput("truven_atc1_plot"),
#plotOutput("truven_icd3_plot")#,
#DT::dataTableOutput("truven_med_history_drug_table")
width = 12,
height = 3000
)
)
Code to create the plot
Server:
# drug cleaveland plot
output$drug_cleveland_plot = renderPlotly({
df <- df_drug_plot()
df <- sqldf("select distinct concept_name,w_cond_rate as rate,'Diagnosed' as grp from df
union
select distinct concept_name,w_exp_rate as rate,'Expected' as grp from df
")
df <- df %>%
arrange(rate) %>% mutate(grp = factor(grp)) %>%
mutate(concept_name=factor(concept_name))
p <- df %>%
arrange(grp, rate, desc(concept_name)) %>%
ggplot(aes(rate, fct_inorder(concept_name))) +
geom_line(aes(group = concept_name)) +
geom_point(aes(color = grp)) +
scale_x_continuous(breaks = seq(0, 1.1, by = 0.1)) +
theme_bw() +
theme(panel.grid.major.x = element_line( linetype = "dotted", size = 0.2, color = 'grey' )) +
scale_colour_manual(values=c("#d91e4a", "#939597")) +
theme (legend.title=element_blank())
m <- list(
l = 200,
r = 100,
b = 100,
t = 100,
pad = 5
)
fig <- ggplotly(p,width = 1500, height = 1000) %>% layout(title = "Drugs: Observed vs Expected Proportion",
autosize = F,
margin = m,
yaxis = list(title = "",
automargin = TRUE),
legend = list(title=list(text='<b> Group </b>')))
fig
})

Alternative to ifelse with radiobutton in R Shiny Dashboard

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

Subset Dataframe and plot with ggplot? [duplicate]

This question already has answers here:
Sort (order) data frame rows by multiple columns
(19 answers)
Closed 4 years ago.
I created a shiny app and need some help with the subset of my data. I insert a dateRangeInput where the client can filter between a start and end date. This filter is included into my ggplot code, so that the plot always automatically changes when a different date is selected. My problem is it does not filter based on the selected date, the data of partC. The problem is this line of code: geom_line(aes(x = Date, y = OLS.Data[partC]), color="red"). partC is a variable that connects to selectinputs to have access to my dataframe. Example: Client selects input1 = Informed and input2 = Full, partC makes InformedFull (which is the name of one column of my dataset) and so on. So partC is just a a connector of the two inputs, and this is my problem. If I put into my geom_line this code e.g geom_line(aes(x = Date, y = InformedFull), color="red"), instead the above everything works perfect, but I need it with partC.
Here is my ui.R code (only necessary part):
box(
title = "Controls-0",
status = "primary",
solidHeader = TRUE,
width = 3,
height = 142,
dateRangeInput("daterange", "SELECT DATE:", start = min(OLS.Data$Date), end = max(OLS.Data$Date))
),
box(
title = "Investor Control",
status = "primary",
solidHeader = TRUE,
width = 3,
selectInput("investor", label="Select Investor", choices = list("Informed" = "Informed", "Noise" = "Noise"), selected = "Informed")
),
box(
title = "Category Control",
status = "primary",
solidHeader = TRUE,
width = 3,
selectInput("category", label="Select Category", choices = list("Full" = "Full", "Fact" = "Fact", "Fact Positive" = "Fact.Pos", "Fact Negative" = "Fact.Neg", "Emotions" = "Emotions", "Emotions Fact" = "EmotionsFact"), selected = "Full")
),
Update server.R with ggplot:
server <- function(input, output) {
partC = NULL
makeReactiveBinding("partC")
observeEvent(input$investor, {
partA<<-input$investor
partA<<-as.character(partA)
})
observeEvent(input$category, {
partB<<-input$category
partB<<-as.character(partB)
})
OLS.Data$InformedEmotionsFact <- as.numeric(as.character(OLS.Data$InformedEmotionsFact))
OLS.Data$NoiseEmotionsFact <- as.numeric(as.character(OLS.Data$NoiseEmotionsFact))
output$myPlotVisu <- renderPlot({
partC<-as.character(paste(partA,partB,sep=""))
OLS.Data %>%
select(partC, NYSE,Date,Sector) %>%
filter(Date >= input$daterange[1], Date <= input$daterange[2]) %>%
ggplot(aes(x = Date, y = NYSE)) +
geom_line() +
ggtitle(paste(input$investor,input$category,sep = "")) +
theme(plot.title = element_text(hjust = 0.5,face="bold")) +
labs(x="Time",y="Return S&P500") +
geom_line(aes(x = Date, y = OLS.Data[partC]), color="red")
})
I dont know why you assign partA/partB to the global environment, and even twice. You dont need to do that. I created an reactiveValues object instead, where you store the values (partA, partB and partC). Then you can use them wherever you want in your app.
Maybe the following example will help you with your code. I created some dummy data for it.
library(shiny)
library(shinydashboard)
library(ggplot2)
## DATA #######################
DateSeq = seq(as.Date("1910/1/1"), as.Date("1911/1/1"), "days")
OLS.Data = data.frame(
ID = 1:length(DateSeq),
Date = DateSeq,
NoiseEmotionsFact = sample(1:100,length(DateSeq), T),
InformedEmotionsFact = sample(100:1000,length(DateSeq), T),
InformedFull = sample(10:1000,length(DateSeq), T),
NoiseFull = sample(50:5000,length(DateSeq), T),
NoiseFact = sample(1:15,length(DateSeq), T),
NoiseFact.Pos = sample(100:110,length(DateSeq), T),
NoiseFact.Pos = sample(10:200,length(DateSeq), T)
)
## UI #######################
ui <- {dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
plotOutput("myPlot"),
box(
title = "Controls-0",
status = "primary",
solidHeader = TRUE,
width = 3,
height = 142,
dateRangeInput("daterange", "SELECT DATE:", start = min(OLS.Data$Date), end = max(OLS.Data$Date))
),
box(
title = "Alpha",
sliderInput("alphaVisu", label = "Alpha :", min = 0, max = 1, value = 0.4, step = 0.1)
),
box(
title = "Investor Control",
status = "primary",
solidHeader = TRUE,
width = 3,
selectInput("investor", label="Select Investor",
choices = list("Informed" = "Informed", "Noise" = "Noise"), selected = "Informed")
),
box(
title = "Category Control",
status = "primary",
solidHeader = TRUE,
width = 3,
selectInput("category", label="Select Category",
choices = list("Full" = "Full", "Fact" = "Fact", "Fact Positive" = "Fact.Pos",
"Fact Negative" = "Fact.Neg", "Emotions" = "Emotions",
"Emotions Fact" = "EmotionsFact"), selected = "Full")
)
)
)}
## SERVER #######################
server <- function(input, output) {
## Reactive Values ############
parts <- reactiveValues(partA=NULL, partB=NULL, partC=NULL)
## Observe Events ############
observeEvent(input$investor, {
parts$partA <- as.character(input$investor)
})
observeEvent(input$category, {
parts$partB <- as.character(input$category)
})
## Plot ############
output$myPlot <- renderPlot({
parts$partC <- as.character(paste(parts$partA, parts$partB,sep=""))
OLS.Data.filtered <- OLS.Data %>%
filter(Date >= input$daterange[1], Date <= input$daterange[2])
req(OLS.Data.filtered)
OLS.Data.filtered %>%
ggplot(aes(x = Date, y = ID)) +
geom_line() +
ggtitle(paste("input$investor","input$category",sep = "")) +
theme(plot.title = element_text(hjust = 0.5,face="bold")) +
labs(x="Time",y="Return S&P500") +
geom_line(aes(x = Date, y = OLS.Data.filtered[parts$partC]), color="red",
alpha = rep(as.numeric(input$alphaVisu), nrow(OLS.Data.filtered[parts$partC])))
})
}
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!!

elements in ui not reactive

I am trying to make reactive elements in my shiny app using RStudio. I want the radio buttons to appear or disappear depending upon a checkbox. Then I am gathering the inputs from the elements displayed to generate two graphs. The problem is that the elements in UI are not reactive. Below is the coding I used.
library(shiny)
library(AER)
library(ggplot2)
library(plotly)
CreditCard <- read.csv("https://gist.githubusercontent.com/anonymous/3ffc253260bae6894c00edb2062729d6/raw/6c08d02eaba4b1691212fd518f2079ef2c112a20/Credit_Card.csv")
key <- read.csv("https://gist.githubusercontent.com/anonymous/9a8c05eb2202d79b03b187117e6fe709/raw/beddca49b669fe5ff27ce7dd1c7bcbe1c4660327/key.csv")
df_cc = CreditCard[sample(nrow(CreditCard), 500), ]
ui <- fluidPage(
title = "Final Project",
sidebarLayout(
sidebarPanel(
conditionalPanel(
'input.tabs === "Graphs"',
checkboxInput("checkbox_facet", label = "Show Facet", value = TRUE),
tags$div(id = 'placeholder'),
selectInput("select_y", label = h4("Select Y-Axis"),
choices = list("Age" = "age", "Income" = "income", "Share" = "share", "Expenditure" = "expenditure", "Months" = "months", "MajorCards" = "majorcards", "Active" = "active"), selected = "active"),
selectInput("select_x", label = h4("Select X-Axis"),
choices = list("Age" = "age", "Income" = "income", "Share" = "share", "Expenditure" = "expenditure", "Months" = "months", "MajorCards" = "majorcards", "Active" = "active"), selected = "income")
) # end conditionalPanel for graphs
), #end sidebarPanel
mainPanel(
tabsetPanel(
id = 'tabs',
tabPanel("Graphs",
plotlyOutput(outputId = "exp"),
plotlyOutput(outputId = "reg"),
uiOutput(outputId = "facet")
) #Graphs
) # end tabsetPanel
) # end mainPanel
) # end sidebarLayout
) # end fluid page
server <- function(input, output) {
observeEvent(input$checkbox_facet, { if (input$checkbox_facet == TRUE) { # radio buttons for facet options show, and graph be made accordingly.
output$facet <- eventReactive(input$checkbox_facet, { insertUI( selector = "#placeholder",
ui = radioButtons("radio_facet", label = h4("Choose Facet Variable"),
choices = list("Card" = "card", "Reports" = "reports", "Owner" = "owner", "SelfEmployed" = "selfemp", "Dependents" = "dependents"), selected = "owner")
) })
output$exp <- eventReactive(input$select_x, { renderPlotly({
ggplotly(
ggplot(df_cc, aes(x=get(input$select_x), y=get(input$select_y))) + geom_point(shape=1) +
facet_wrap(~get(input$radio_facet), labeller = label_both) +
labs(title = "Exploratory Plot", x = input$select_x, y = input$select_y)
)
})
})
output$reg <- eventReactive(input$select_x, { renderPlotly({
ggplotly(
ggplot(df_cc, aes(x=get(input$select_x), y=get(input$select_y))) + geom_point(shape=1) +
geom_smooth(method = "glm", family = "poisson", se = FALSE) +
facet_wrap(~get(input$radio_facet), labeller = label_both) +
labs(title = "Poisson Regression", x = input$select_x, y = input$select_y)
)
})
})
}
else { # radio buttons disappear and graph is without facets
output$facet <- eventReactive(input$checkbox_facet, { removeUI(selector = 'div:has(> #radio_facet)', immediate = TRUE) })
output$exp <- eventReactive(input$select_x, { renderPlotly({
ggplotly(
ggplot(df_cc, aes(x=get(input$select_x), y=get(input$select_y))) + geom_point(shape=1) +
labs(title = "Exploratory Plot", x = input$select_x, y = input$select_y)
)
})
})
output$reg <- eventReactive(input$select_x, { renderPlotly({
ggplotly(
ggplot(df_cc, aes(x=get(input$select_x), y=get(input$select_y))) + geom_point(shape=1) +
geom_smooth(method = "glm", family = "poisson", se = FALSE) +
labs(title = "Poisson Regression", x = input$select_x, y = input$select_y)
)
})
})
}
}) # end observeEvent for graphs
}
shinyApp(ui, server)
You're just overcomplicating things.
In your code, you have reactive expressions, that reactively assign other reactive expressions. So you always fight with a double layer of reactivity.
I don't know if you noticed, but you also delete the placeholder div the first time the checkbox is unchecked. You maybe did this on purpose, because otherwise the radio buttons will always be there. Because overwriting the output$facet will not delete any reacting expressions. And your reactive logic itself does not contain the state of input$checkbox_facet. So you are always fighting with reactive expressions, that you reassign and where you have no control over how they are executed.
What I recommend is, to clean up your code. Pick each output element by itself and define what reactions you really want to happen. And then define a fixed behaviour, that reflects that.
Also, be aware that render functions are reactive environments by default.
Below is a refactoring that works:
library(shiny)
library(AER)
library(ggplot2)
library(plotly)
CreditCard <- read.csv("https://gist.githubusercontent.com/anonymous/3ffc253260bae6894c00edb2062729d6/raw/6c08d02eaba4b1691212fd518f2079ef2c112a20/Credit_Card.csv")
key <- read.csv("https://gist.githubusercontent.com/anonymous/9a8c05eb2202d79b03b187117e6fe709/raw/beddca49b669fe5ff27ce7dd1c7bcbe1c4660327/key.csv")
df_cc = CreditCard[sample(nrow(CreditCard), 500), ]
ui <- fluidPage(
title = "Final Project",
sidebarLayout(
sidebarPanel(
conditionalPanel(
'input.tabs === "Graphs"',
checkboxInput("checkbox_facet", label = "Show Facet", value = TRUE),
uiOutput("facets"),
selectInput("select_y", label = h4("Select Y-Axis"),
choices = list("Age" = "age", "Income" = "income", "Share" = "share", "Expenditure" = "expenditure", "Months" = "months", "MajorCards" = "majorcards", "Active" = "active"), selected = "active"),
selectInput("select_x", label = h4("Select X-Axis"),
choices = list("Age" = "age", "Income" = "income", "Share" = "share", "Expenditure" = "expenditure", "Months" = "months", "MajorCards" = "majorcards", "Active" = "active"), selected = "income")
) # end conditionalPanel for graphs
), #end sidebarPanel
mainPanel(
tabsetPanel(
id = 'tabs',
tabPanel("Graphs",
plotlyOutput(outputId = "exp"),
plotlyOutput(outputId = "reg")
) #Graphs
) # end tabsetPanel
) # end mainPanel
) # end sidebarLayout
) # end fluid page
server <- function(input, output) {
output$facets <- renderUI({
if (input$checkbox_facet) {
radioButtons("radio_facet",
label = h4("Choose Facet Variable"),
choices = list("Card" = "card", "Reports" = "reports", "Owner" = "owner", "SelfEmployed" = "selfemp", "Dependents" = "dependents"),
selected = "owner"
)
}
})
output$exp <- renderPlotly({
g <- ggplot(df_cc, aes(x=get(input$select_x), y=get(input$select_y))) +
geom_point(shape=1) +
labs(title = "Exploratory Plot", x = input$select_x, y = input$select_y)
if (input$checkbox_facet) {
g <- g + facet_wrap(~get(input$radio_facet), labeller = label_both)
}
ggplotly(g)
})
output$reg <- renderPlotly({
g <- ggplot(df_cc, aes(x=get(input$select_x), y=get(input$select_y))) +
geom_point(shape=1) +
geom_smooth(method = "glm", family = "poisson", se = FALSE) +
labs(title = "Poisson Regression", x = input$select_x, y = input$select_y)
if (input$checkbox_facet) {
g <- g + facet_wrap(~get(input$radio_facet), labeller = label_both)
}
ggplotly(g)
})
}
shinyApp(ui, server)
To address the comment from Gregor de Cillia about conditional panels: You might not want to recreate the radio buttons every time the checkbox changes, since the options are in fact always the same. (And you might want to keep the state, i.e. which item was selected previously.) A conditionalPanel just hides the radio buttons and therefore cleans up your server code even more.
Example below:
library(shiny)
library(AER)
library(ggplot2)
library(plotly)
CreditCard <- read.csv("https://gist.githubusercontent.com/anonymous/3ffc253260bae6894c00edb2062729d6/raw/6c08d02eaba4b1691212fd518f2079ef2c112a20/Credit_Card.csv")
key <- read.csv("https://gist.githubusercontent.com/anonymous/9a8c05eb2202d79b03b187117e6fe709/raw/beddca49b669fe5ff27ce7dd1c7bcbe1c4660327/key.csv")
df_cc = CreditCard[sample(nrow(CreditCard), 500), ]
ui <- fluidPage(
title = "Final Project",
sidebarLayout(
sidebarPanel(
conditionalPanel(
'input.tabs === "Graphs"',
checkboxInput("checkbox_facet", label = "Show Facet", value = TRUE),
conditionalPanel('input.checkbox_facet',
radioButtons("radio_facet",
label = h4("Choose Facet Variable"),
choices = list("Card" = "card", "Reports" = "reports", "Owner" = "owner", "SelfEmployed" = "selfemp", "Dependents" = "dependents"),
selected = "owner"
)
),
selectInput("select_y", label = h4("Select Y-Axis"),
choices = list("Age" = "age", "Income" = "income", "Share" = "share", "Expenditure" = "expenditure", "Months" = "months", "MajorCards" = "majorcards", "Active" = "active"), selected = "active"),
selectInput("select_x", label = h4("Select X-Axis"),
choices = list("Age" = "age", "Income" = "income", "Share" = "share", "Expenditure" = "expenditure", "Months" = "months", "MajorCards" = "majorcards", "Active" = "active"), selected = "income")
) # end conditionalPanel for graphs
), #end sidebarPanel
mainPanel(
tabsetPanel(
id = 'tabs',
tabPanel("Graphs",
plotlyOutput(outputId = "exp"),
plotlyOutput(outputId = "reg")
) #Graphs
) # end tabsetPanel
) # end mainPanel
) # end sidebarLayout
) # end fluid page
server <- function(input, output) {
output$exp <- renderPlotly({
g <- ggplot(df_cc, aes(x=get(input$select_x), y=get(input$select_y))) +
geom_point(shape=1) +
labs(title = "Exploratory Plot", x = input$select_x, y = input$select_y)
if (input$checkbox_facet) {
g <- g + facet_wrap(~get(input$radio_facet), labeller = label_both)
}
ggplotly(g)
})
output$reg <- renderPlotly({
g <- ggplot(df_cc, aes(x=get(input$select_x), y=get(input$select_y))) +
geom_point(shape=1) +
geom_smooth(method = "glm", family = "poisson", se = FALSE) +
labs(title = "Poisson Regression", x = input$select_x, y = input$select_y)
if (input$checkbox_facet) {
g <- g + facet_wrap(~get(input$radio_facet), labeller = label_both)
}
ggplotly(g)
})
}
shinyApp(ui, server)

Resources