R shiny tabbox plot overlapping - r

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
})

Related

How do I dynamically update a calculated value based on the number of input values in R Shiny?

I am trying to update the value in a plotly chart in R shiny whose calculated value depends on the number of inputs
library(shiny)
library(httr)
library(jsonlite)
library(dplyr)
library(plotly)
library(shinythemes)
library(flexdashboard)
library(shinydashboard)
setwd("X:/Work/Covid-19 Project/Shiny Dashboard")
rp_1 <- read.csv("Data/Risk Profile 1.csv")
rp_2 <- read.csv("Data/Risk Profile 2.csv")
gender <- c("Male","Female")
age <- c("Less than 20 years", "20 to 50 years","More than 50 years")
city <- c("Delhi","Chennai")
diabetes <- c("Have diabetes","Don't have diabetes")
hypertension <- c("Have hypertension","Don't have hypertension")
risk_level_est <- function(city, gender, age, db, ht){
p_inv <- as.numeric(rp_1 %>%
filter(City == city & Gender == gender) %>%
select(Prob))
p_adv <- as.numeric(rp_2 %>%
filter(Age == age & Diabetes == db & Hypertension == ht) %>%
summarise(Hosp + Death))
as.numeric(p_inv*p_adv*100)
}
sar_risk_level_est <- function(age, db, ht){
p_adv <- as.numeric(rp_2 %>%
filter(Age == age & Diabetes == db & Hypertension == ht) %>%
summarise(Hosp + Death))
as.numeric(0.2*p_adv*100)
}
about_page <- tabPanel(
title = "About",
titlePanel("About"),
"Created with R Shiny",
br(),
"2021 April"
)
main_page <- tabPanel(
title = "Estimator",
titlePanel(""),
sidebarLayout(
sidebarPanel(
title = "Inputs",
selectInput("gender", "Select your gender", gender),
selectInput("age", "Select your age", age),
selectInput("city", "Select your city", city),
selectInput("db", "Do you have diabetes", diabetes),
selectInput("ht", "Do you have hypertension", hypertension),
radioButtons("radio", "Do you want to include your household members",
choices = list("No" = 1,"Yes" = 2)),
conditionalPanel("input.radio == 2",
numericInput("members", label = "How many household members do you have?", value='1'),
uiOutput("member_input")
),
actionButton("risk","Calculate my risk profile")
),
mainPanel(
tabsetPanel(
tabPanel(
title = "Risk Profile",
plotlyOutput("risk_profile", height = 250, width = "75%"),
plotlyOutput("overall_risk_profile", height = 250, width = "75%")
)
)
)
)
)
ui <- navbarPage(
title = "Risk Estimator",
theme = shinytheme('united'),
main_page,
about_page
)
server <- function(input, output, session) {
output$member_input <- renderUI({
numMembers <- as.integer(input$members)
lapply(1:numMembers, function(i) {
list(tags$p(tags$u(h4(paste0("Member ", i)))),
selectInput(paste0("age", i), "Select their age", age, selected = NULL),
selectInput(paste0("db", i), "Do they have diabetes", diabetes, selected = NULL),
selectInput(paste0("ht", i), "Do they have hypertension", hypertension, selected = NULL))
})
})
risk_level <- eventReactive(input$risk, {
risk_level_est(input$city, input$gender, input$age, input$db, input$ht)
})
sar_risk_level <- eventReactive(input$risk,{
sar_risk <- 0
lapply(1:input$members, function(i){
sar_risk <- sar_risk + sar_risk_level_est(input[[paste0("age", i)]],input[[paste0("db", i)]],input[[paste0("ht", i)]])
})
as.numeric(sar_risk)
})
output$risk_profile <- renderPlotly({
fig <- plot_ly(
domain = list(x = c(0, 1), y = c(0, 1)),
value = risk_level(),
title = list(text = "Personal Risk Profile"),
type = "indicator",
mode = "gauge+number",
gauge = list(
axis = list(range = list(0, 15)),
bar = list(color = "gray"),
bgcolor = "white",
borderwidth = 2,
bordercolor = "gray",
steps = list(
list(range = c(0, 3.75), color = "darkgreen"),
list(range = c(3.75, 7.5), color = "chartreuse"),
list(range = c(7.5,11.25), color = "orange"),
list(range = c(11.25,15), color = "red")
)))
fig <- fig %>% layout(margin = list(l=30, r=30, t=80, b=30))
fig
})
output$overall_risk_profile <- renderPlotly({
fig <- plot_ly(
domain = list(x = c(0, 1), y = c(0, 1)),
value = risk_level() + sar_risk_level(),
title = list(text = "Overall Risk Profile"),
type = "indicator",
mode = "gauge+number",
gauge = list(
axis = list(range = list(0, 15+(25*input*members))),
bar = list(color = "gray"),
bgcolor = "white",
borderwidth = 2,
bordercolor = "gray",
steps = list(
list(range = c(0, 3.75), color = "darkgreen"),
list(range = c(3.75, 7.5), color = "chartreuse"),
list(range = c(7.5,11.25), color = "orange"),
list(range = c(11.25,15), color = "red")
)))
fig <- fig %>% layout(margin = list(l=30, r=30, t=80, b=30))
fig
})
}
shinyApp(ui, server)
While the risk_profile plot works fine, the overall_risk_profile plot throws the "non-numeric argument to binary operator" error. The sar_risk_level() value in overall_risk_profile is dependent on a calculation (sar_risk_level_est) which depends on the number of inputs. I want this value (sar_risk) to be initizialied to zero and updated everytime the action button is pressed.
Great looking app. I think it is just a typo. The code has 25*input*members instead of 25*input$members on line 151.

How to adapt the height of an HTML widget to the height of the window in R Shiny?

How to adapt it so that it can be correctly rendered on different screens?
(height = "100%" and height = "auto" don't work)
I have to add text that is not code
I have to add text that is not code
I have to add text that is not code
I have to add text that is not code
I have to add text that is not code
[EDIT] Reprex below
RequiredLibraries <- c("data.table", "visNetwork", "shiny")
RequiredLibraries2Install <- RequiredLibraries[!(RequiredLibraries %in% installed.packages()[, "Package"])]
if(length(RequiredLibraries2Install)) install.packages(RequiredLibraries2Install, dependencies = TRUE)
lapply(RequiredLibraries, library, character.only = TRUE)
ui <- fluidPage(
titlePanel(windowTitle = "Application Title", title = "Application Title"),
sidebarLayout(
sidebarPanel(
h4("Year End"),
#hr(),
selectInput(inputId = "YE", label = "Year End", choices = 2016:2020, selected = c(2018), multiple = FALSE, selectize = FALSE),
width = 2
),
mainPanel(
# Freeze the main (on the right) panel and leave the sidebar (on the left) panel scrollable
style = "position:fixed;left:17%;",
tabsetPanel(type = "tabs",
tabPanel("Network",
visNetworkOutput(outputId = "Network", width = "100%", height = "75vh")
),
tabPanel(actionLink(inputId = "Download.Network.Data", label = "Download current network data", icon = icon(name = "download", class = NULL, lib = "font-awesome"))
)
),
width = 10
)
)
)
server <- function(input, output, session)
{
GenerateNetwork <- reactive({
# Taken from https://datastorm-open.github.io/visNetwork/edges.html
Links <- data.frame(from = sample(1:10, 8), to = sample(1:10, 8),
# add labels on edges
label = paste("Edge", 1:8),
# length
length = c(100, 500),
# width
width = c(4, 1),
# arrows
arrows = c("to", "from", "middle", "middle;to"),
# dashes
dashes = c(TRUE, FALSE),
# tooltip (html or character)
title = paste("Edge", 1:8),
# smooth
smooth = c(FALSE, TRUE),
# shadow
shadow = c(FALSE, TRUE, FALSE, TRUE)
)
Nodes <- data.frame(id = 1:10, group = c("A", "B"))
visNetwork(Nodes, Links, width = "100%", height = "700px", main = "Network Title") %>%
visInteraction(navigationButtons = TRUE, keyboard = TRUE) %>%
visPhysics(stabilization = TRUE) %>%
#visLegend(addNodes = Legend.Nodes, addEdges = Legend.Links, useGroups = FALSE, width = 0.25, position = "right", main = "Network Legend", ncol = 1) %>%
visLayout(randomSeed = 123)
})
# Create the output Network
output$Network <- renderVisNetwork(GenerateNetwork())
}
shinyApp(ui = ui, server = server, enableBookmarking = "server")
Use the CSS unit vh. E.g. 100vh, that means 100% of the height of the viewport. You can also try fit-content.

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)

render the clicked tab R dashboard

I am working on shinydashboard app with multiple tabs & I would like to render the tab content only when it is clicked on. I'm using shinydashboard library to create my dashboard, the application takes around 30 sec to work and I would like to optimize it so it will render the selected tab only.
UI code sample
dashboardPage(
dashboardHeader(title = "Enrollment Dashboard",titleWidth = 300),
sidebar <- dashboardSidebar(width = 300,
sidebarMenu(
menuItem("Descriptive Analysis", icon = icon("right",lib='glyphicon'), tabName = "desc",
menuSubItem("Statistics",icon = icon("right",lib='glyphicon'),tabName = "kpi" ),
menuSubItem("Marketing" ,icon = icon("right",lib='glyphicon'), tabName = "markd")),
menuItem("Predictive Analysis", icon = icon("right",lib='glyphicon'), tabName = "predictive",
menuItem("Enrollment Number", icon = icon("right",lib='glyphicon'), tabName = "predictive",
menuSubItem("Enrollment prediction - overall" ,icon = icon("right",lib='glyphicon'), tabName = "predictivesummary"),
menuItem("Enrollment prediction per program" , icon = icon("right",lib='glyphicon'),tabName = "predictiveprograms"))
dashboardBody(
tags$head(tags$link(rel = "stylesheet" , type = "text/css" , href = "reload.CSS")),
renderText("test"),
tabItems(tabItem(tabName = "kpi",
frow1<-fluidRow(
infoBoxOutput("value1",width = 3),tags$style("#value1 { padding-top:0px; padding-bottom:0px;color: blue; font-size: 13px;background:#F4F4F4;}"),
infoBoxOutput("value2",width = 3),tags$style("#value2 { padding-top:0px; padding-bottom:0px;color: blue; font-size: 13px;background:#F4F4F4;}"),
box
(uiOutput("value3"),
width = 1,
height = 130
),
box
(uiOutput("value5"),
width = 1,
height = 130
),
box
(uiOutput("value6"),
width = 1,
height = 130
),
infoBoxOutput("value4",width = 3),tags$style("#value4 {padding-top:0px; padding-bottom:0px;color: blue; font-size: 13px;background:#F4F4F4;}")
),
frow2<-fluidRow(
box(
title = "Inquiry (Actuals- Green/Target- Light Grey)"
,width = 3
,height = 330
,status = "warning"
,solidHeader = FALSE
,collapsible = TRUE
,dataTableOutput("plot")
),
box(
title = "Applied (Actuals- Green/Target- Light Grey)"
,width = 3
,status = "warning"
,solidHeader = FALSE
,collapsible = TRUE
,plotlyOutput("applyplot", height = 270)
),
box(
title = "Processed (Actuals- Green/Target- Light Grey)"
,width = 3
,status = "warning"
,solidHeader = FALSE
,collapsible = TRUE
,plotlyOutput("processedplot", height = 270)
),
box(
title = "Enrolled (Actuals- Green/Target- Light Grey)"
,width = 3
,status = "warning"
,solidHeader = FALSE
,collapsible = TRUE
,plotlyOutput("enrolledplot", height = 270)
)),
frow3<-fluidRow(
box(
title = "Enrollment Yearly Progress Growth / Programs "
,width = 12
,solidHeader = FALSE
,collapsible = TRUE
,status = "warning",
tabsetPanel( type = 'pills',
tabPanel('Admissions',
plotlyOutput("threerow", height = 350)
),
tabPanel('Financial',plotlyOutput("frow", height = 350)),
tabPanel('Enrollment',plotlyOutput("erow", height = 350))
)
))
),
tabItem(tabName = "predictivesummary" ,
frow5<- fluidRow(
box("Yearly Predictive Analysis"
,width = 12
,solidHeader = FALSE
,collapsible = TRUE
,status = "warning"
,plotlyOutput("plot_forecast" , height = 350) )),
frow501<- fluidRow(
box("Overall Prediction Yearly - Tabular"
,width = 12
,solidHeader = FALSE
,collapsible = TRUE
,status = "warning"
,dataTableOutput("year_table" , height = 350) ))
)
Server
shinyServer(function(input, output ,session ) {
output$value1 <- renderInfoBox({
infoBox(
h2(total.TotalInquiry()),
h4(percentage.TotalInquiry())
,tags$h5('Inquries - Target : ' , total.TargetInquiry())
,
icon = icon("question-sign",lib='glyphicon')
)})
output$value2 <- renderInfoBox({
infoBox(
h2(total.Applied()),
h4(percentage.Applied())
,h5('Applied-Target:',target.Applied())
,
icon = icon("thumbs-up",lib='glyphicon'))
})
output$value3 <- renderText({
paste0(h3(ProcessedA.Accepted()) ,
paste0(percentagepA.Accepted(),'%'),
paste0(),
h5('Processed:' , ProcessedT.Accepted()))
})
output$value5 <- renderText({enter code here
paste0(h3(Processed.Rejected()),h6('Rejected:' ))
})
output$value6 <- renderText({
paste0(h3(Processed.Dropped()),h6('Withdrawan:' ))
})
output$value4 <- renderInfoBox({
infoBox(
#tags$h2(total.enrolled() ,'~' , percentage.enrolled())
tags$h2(total.enrolled()),
h4(percentage.enrolled())
,tags$h5('Enrolled-Target:',target.enrolled())
,
#color = "olive" , fill = TRUE
icon = icon("check",lib='glyphicon') )
})
output$plot <- DT::renderDataTable(expr ={
g <- IA.Applied()
} , options = list(dom = 't',scrollX = TRUE,autowidth = TRUE,columnDefs = list(list(width = '10px', targets = c(1,3)))))
output$applyplot <- renderPlotly(expr ={
g <- IAA.Applied() %>%
mutate(group = 1) %>%
ggplot(aes(Program, Applied_Act)) +
ylim(0,150)+
geom_col(fill = "#b0e0e6") +
geom_text(aes(label = Applied), position = position_dodge(0.3),family = "Times New Roman",size = 3)+
geom_col(aes(y = applied_Tar, group = group), color = "#e7e7e7" ,fill = "#A3A9D1", alpha=0.3) +
theme_classic()+
labs(x = "", y = "")
ggplotly(g, tooltip = "Applied")
})
output$processedplot <- renderPlotly(expr ={
g <- IA.processed() %>%
mutate(group = 1) %>%
ggplot(aes(Program, Act_Processed)) +
ylim(0,150)+
geom_col(fill = "#b0e0e6") +
geom_text(aes(label = Processed), position = position_dodge(0.3),family = "Times New Roman",size = 3)+
geom_col(aes(y = Tar_processed, group = group), color = "#e7e7e7" ,fill = "#A3A9D1", alpha=0.3) +
theme_classic()+
labs(x = "", y = "")
ggplotly(g, tooltip = "Processed")
})
#SmokeyShakers is right, Shiny is built so that the server side only renders when visible (i.e. you click on a tab or unhide a table).
I would look at the data you are pulling in and any data manipulation you are doing and seeing if that is the cause of the 30 seconds.
I would use the package profvis to do an analysis on your app.
If the data manipulation/reading is the cause there are multiple options such as running a separate process to do the data manipulation and putting the data into a global variable.

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)

Resources