Related
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
})
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)
For simplicity, assume the BTC, ETH, XRP data is an arbitrary list of numbers ie: 4000, 5000, 500 etc. The data from the web and my excel files is not implemented this version and I have added fake data for anyone to recreate my problem with the Plots. My problem is that everything works and the dashboard comes up, but the plots will not appear. It has something to do with my server function, and I know It needs to be reactive in some form. I have not found a solution that fixes my problem. let me know if I can help in any way or answer any questions. Thanks! (I also know not all library functions are being used at this moment)
Additionally, if anyone knows how to implement the selected dates as the used input for the plots that would be awesome as well! Right now I am using a slider input for simplicity. I will also change the plot to a line graph. For now, if someone could help me with the reactivity that would be great!
`
library(shiny)
library(shinydashboard)
library(ggplot2)
library(gdata)
library(rvest)
# setwd("C:/Users/Zach/Documents/app.R/fuckk you")
# url <- "https://coinmarketcap.com/currencies/bitcoin/historical-data/?start=20130428&end=20180811"
# BTCALL <- url %>%
# html() %>%
# html_nodes(xpath='//*[#id="historical-data"]/div/div[2]/table') %>%
# html_table()
# BTCALL <- BTCALL[[1]]
#
# url <- "https://coinmarketcap.com/currencies/ethereum/historical-data/?start=20130428&end=20180811"
# ETHALL <- url %>%
# html() %>%
# html_nodes(xpath='//*[#id="historical-data"]/div/div[2]/table') %>%
# html_table()
# ETHALL <- ETHALL[[1]]
#
# url <- "https://coinmarketcap.com/currencies/ripple/historical-data/?start=20130428&end=20180811"
# XRPALL <- url %>%
# html() %>%
# html_nodes(xpath='//*[#id="historical-data"]/div/div[2]/table') %>%
# html_table()
# XRPALL <- XRPALL[[1]]
# df <- read.xls("Rdata.xlsx",
# sheet = 1,
# perl="c:/Perl64/bin/perl")
#
# BTC <- df[,2]
# ETH <- df[,3]
# XRP <- df[,4]
# DataDate <- df[,1]
Date <- Sys.Date()
class(as.Date(Date))
Start <- Date
End <- Date+8
BTC = c(5000,6000,7000,8000,9000,10000,11000,12000)
ETH = c(300,400,500,600,700,800,900,1000,1100,1200)
XRP = c(.2,.3,.4,.5,.6,.7,.8,.9,1,1.1,1.2,1.3,1.4)
ui <- fluidPage(
dashboardPage( skin = "black",
dashboardHeader(title = tags$a(tags$img(src="Apollo.png", height ='58', width ='220'),
'Apollo Projections'),
dropdownMenu(type = "message",
messageItem(from = "btc Updates", message = "BTC ETF to be launched soon", time = "12:00")
),
dropdownMenu(type = "notifications",
notificationItem(
text = "2 new tabs added!",
icon = icon("dashboard"),
status = "success"
)
),
dropdownMenu(type = "tasks",
taskItem(
value = 62,
color = "red",
text = "Read BTC manuel"
),
taskItem(
value = 22,
color = "aqua",
text = "Read ETH manuel"
))
),
dashboardSidebar(
sidebarMenu(
menuItem("BTC", tabName = "BTC",icon = icon("bitcoin")),
menuSubItem("Volume", tabName = "BTCV"),
menuSubItem("MarketCap", tabName = "BTCM"),
menuItem("ETH", tabName = "Eth"),
menuItem("XRP", tabName = "Xrp", badgeLabel = "New", badgeColor = "aqua")
)
),
dashboardBody(
tabItems(
tabItem(tabName = "BTC",
fluidRow(
infoBox("Current BTC Price Change",paste("%",round(BTC/BTC,digits = 4)), icon = icon("bitcoin")),
infoBox("Tomorrow BTC Price Change",paste("%",round(BTC[2]/BTC,digits = 4)), icon = icon("warning"), color = "blue"),
infoBox("Weekly BTC Price Change",paste("%",round(BTC[7]/BTC,digits = 4)), icon = icon("bar-chart-o"), color = "red")
),
fluidRow(
valueBox(paste("$",round(BTC,digits = 2)), "BTC Price Today", icon = icon("hourglass-3")),
valueBox(paste("$",round(BTC[2],digits = 2)), "BTC Price Tomorrow", icon = icon("diamond"), color = "blue"),
valueBox(paste("$",round(BTC[7],digits = 2)), "BTC Price in 1 Week", icon = icon("globe"),color ="red")
),
fluidRow(
box(title = "BTC Projections", status = "primary", solidHeader = T, plotOutput("Bhisto", height = "500px")),
box (title = "Controls for BTC", status = "primary", solidHeader = T,
sliderInput("NUM","Days for BTC",1,100,50),
dateInput("BTCdate1", "Starting Date", value = Date), dateInput("BTCdate2", "Ending Date", value = Date+6)),
##function for Chart
Final <- difftime(End ,Start , units = c("days")),
textOutput(Final)
)),
tabItem(tabName = "BTCV",
h1("BTC Volume Projections")
),
tabItem(tabName = "BTCM",
h1("BTC MarketCap Projections")
),
tabItem(tabName = "Eth",
fluidRow(
infoBox("Current ETH Price Change",paste("%",round(ETH/ETH,digits = 4)), icon = icon("bitcoin")),
infoBox("Tomorrow ETH Price Change",paste("%",round(ETH[2]/ETH,digits = 4)), icon = icon("warning"), color = "blue"),
infoBox("Weekly ETH Price Change",paste("%",round(ETH[7]/ETH,digits = 4)), icon = icon("bar-chart-o"), color = "red")
),
fluidRow(
valueBox(paste("$",round(ETH,digits = 2)), "ETH Price Today", icon = icon("hourglass-3")),
valueBox(paste("$",round(ETH[2],digits = 2)), "ETH Price Tomorrow", icon = icon("diamond"), color = "blue"),
valueBox(paste("$",round(ETH[7],digits = 2)), "ETH Price in 1 Week", icon = icon("globe"),color ="red")
),
fluidRow(
box(title = "ETH Projections", status = "primary", solidHeader = T, plotOutput("Ehisto", height = "500px")),
box (title = "Controls for ETH", status = "primary", solidHeader = T,
sliderInput("NUM2","Days for ETH",1,100,50),
dateInput("ETHdate1", "Starting Date", value = Date), dateInput("ETHdate2", "Ending Date", value = Date+6)),
##function for Chart
Final <- difftime(End ,Start , units = c("days")),
textOutput(Final)
)),
tabItem(tabName = "Xrp",
fluidRow(
infoBox("Current XRP Price Change",paste("%",round(XRP/XRP,digits = 4)), icon = icon("bitcoin")),
infoBox("Tomorrow XRP Price Change",paste("%",round(XRP[2]/XRP,digits = 4)), icon = icon("warning"), color = "blue"),
infoBox("Weekly XRP Price Change",paste("%",round(XRP[7]/XRP,digits = 4)), icon = icon("bar-chart-o"), color = "red")
),
fluidRow(
valueBox(paste("$",round(XRP,digits = 2)), "XRP Price Today", icon = icon("hourglass-3")),
valueBox(paste("$",round(XRP[2],digits = 2)), "XRP Price Tomorrow", icon = icon("diamond"), color = "blue"),
valueBox(paste("$",round(XRP[7],digits = 2)), "XRP Price in 1 Week", icon = icon("globe"),color ="red")
),
fluidRow(
box(title = "XRP Projections", status = "primary", solidHeader = T, plotOutput("Xhisto", height = "500px")),
box (title = "Controls for XRP", status = "primary", solidHeader = T,
sliderInput("NUM3","Days for XRP",1,100,50),
dateInput("XRPdate1", "Starting Date", value = Date), dateInput("XRPdate2", "Ending Date", value = Date+6)),
##function for Chart
Final <- difftime(End ,Start , units = c("days")),
textOutput(Final)
))
)
)
)
)
server = function(input, output){
output$Bhisto <- renderPlot({
plot(BTC,breaks = input$NUM)
})
output$Ehisto <- renderPlot({
plot(ETH,breaks = input$NUM2)
})
output$Xhisto <- renderPlot({
plot(XRP,breaks = input$NUM3)
})
}
shinyApp(ui = ui, server = server)
`
The problem was the elements not enclosed in the box(). namely Function for Chart in all three tabItems.
I have commented out the two lines in each tabItem
# Final <- difftime(End ,Start , units = c("days")),
# textOutput(Final)
I am not sure what you are trying to do with the above two lines. Here are a few pointers:
If you are looking to use an input value in ui, you can use input.inputId (in the server you will use input$inputId)
Use box() around this textOutput()
Move fixed calculations (like Final) out of ui.
Also, check the warning messages you are getting in the console when you run the app.
Here is the working code:
library(shiny)
library(shinydashboard)
library(ggplot2)
library(gdata)
library(rvest)
# setwd("C:/Users/Zach/Documents/app.R/fuckk you")
# url <- "https://coinmarketcap.com/currencies/bitcoin/historical-data/?start=20130428&end=20180811"
# BTCALL <- url %>%
# html() %>%
# html_nodes(xpath='//*[#id="historical-data"]/div/div[2]/table') %>%
# html_table()
# BTCALL <- BTCALL[[1]]
#
# url <- "https://coinmarketcap.com/currencies/ethereum/historical-data/?start=20130428&end=20180811"
# ETHALL <- url %>%
# html() %>%
# html_nodes(xpath='//*[#id="historical-data"]/div/div[2]/table') %>%
# html_table()
# ETHALL <- ETHALL[[1]]
#
# url <- "https://coinmarketcap.com/currencies/ripple/historical-data/?start=20130428&end=20180811"
# XRPALL <- url %>%
# html() %>%
# html_nodes(xpath='//*[#id="historical-data"]/div/div[2]/table') %>%
# html_table()
# XRPALL <- XRPALL[[1]]
# df <- read.xls("Rdata.xlsx",
# sheet = 1,
# perl="c:/Perl64/bin/perl")
#
# BTC <- df[,2]
# ETH <- df[,3]
# XRP <- df[,4]
# DataDate <- df[,1]
Date <- Sys.Date()
class(as.Date(Date))
Start <- Date
End <- Date+8
BTC = c(5000,6000,7000,8000,9000,10000,11000,12000)
ETH = c(300,400,500,600,700,800,900,1000,1100,1200)
XRP = c(.2,.3,.4,.5,.6,.7,.8,.9,1,1.1,1.2,1.3,1.4)
ui <- fluidPage(
dashboardPage( skin = "black",
dashboardHeader(title = tags$a(tags$img(src="Apollo.png", height ='58', width ='220'),
'Apollo Projections'),
dropdownMenu(type = "message",
messageItem(from = "btc Updates", message = "BTC ETF to be launched soon", time = "12:00")
),
dropdownMenu(type = "notifications",
notificationItem(
text = "2 new tabs added!",
icon = icon("dashboard"),
status = "success"
)
),
dropdownMenu(type = "tasks",
taskItem(
value = 62,
color = "red",
text = "Read BTC manuel"
),
taskItem(
value = 22,
color = "aqua",
text = "Read ETH manuel"
))
),
dashboardSidebar(
sidebarMenu(
menuItem("BTC", tabName = "BTC",icon = icon("bitcoin")),
menuSubItem("Volume", tabName = "BTCV"),
menuSubItem("MarketCap", tabName = "BTCM"),
menuItem("ETH", tabName = "Eth"),
menuItem("XRP", tabName = "Xrp", badgeLabel = "New", badgeColor = "aqua")
)
),
dashboardBody(
tabItems(
tabItem(tabName = "BTC",
fluidRow(
infoBox("Current BTC Price Change",paste("%",round(BTC/BTC,digits = 4)), icon = icon("bitcoin")),
infoBox("Tomorrow BTC Price Change",paste("%",round(BTC[2]/BTC,digits = 4)), icon = icon("warning"), color = "blue"),
infoBox("Weekly BTC Price Change",paste("%",round(BTC[7]/BTC,digits = 4)), icon = icon("bar-chart-o"), color = "red")
),
fluidRow(
valueBox(paste("$",round(BTC,digits = 2)), "BTC Price Today", icon = icon("hourglass-3")),
valueBox(paste("$",round(BTC[2],digits = 2)), "BTC Price Tomorrow", icon = icon("diamond"), color = "blue"),
valueBox(paste("$",round(BTC[7],digits = 2)), "BTC Price in 1 Week", icon = icon("globe"),color ="red")
),
fluidRow(
box(title = "BTC Projections", status = "primary", solidHeader = T, plotOutput("Bhisto")),
box (title = "Controls for BTC", status = "primary", solidHeader = T,
sliderInput("NUM","Days for BTC",1,100,50),
dateInput("BTCdate1", "Starting Date", value = Date), dateInput("BTCdate2", "Ending Date", value = Date+6))
##function for Chart
# Final <- difftime(End ,Start , units = c("days")),
# textOutput(Final)
)),
tabItem(tabName = "BTCV",
h1("BTC Volume Projections")
),
tabItem(tabName = "BTCM",
h1("BTC MarketCap Projections")
),
tabItem(tabName = "Eth",
fluidRow(
infoBox("Current ETH Price Change",paste("%",round(ETH/ETH,digits = 4)), icon = icon("bitcoin")),
infoBox("Tomorrow ETH Price Change",paste("%",round(ETH[2]/ETH,digits = 4)), icon = icon("warning"), color = "blue"),
infoBox("Weekly ETH Price Change",paste("%",round(ETH[7]/ETH,digits = 4)), icon = icon("bar-chart-o"), color = "red")
),
fluidRow(
valueBox(paste("$",round(ETH,digits = 2)), "ETH Price Today", icon = icon("hourglass-3")),
valueBox(paste("$",round(ETH[2],digits = 2)), "ETH Price Tomorrow", icon = icon("diamond"), color = "blue"),
valueBox(paste("$",round(ETH[7],digits = 2)), "ETH Price in 1 Week", icon = icon("globe"),color ="red")
),
fluidRow(
box(title = "ETH Projections", status = "primary", solidHeader = T, plotOutput("Ehisto", height = "500px")),
box (title = "Controls for ETH", status = "primary", solidHeader = T,
sliderInput("NUM2","Days for ETH",1,100,50),
dateInput("ETHdate1", "Starting Date", value = Date), dateInput("ETHdate2", "Ending Date", value = Date+6))
##function for Chart
# Final <- difftime(End ,Start , units = c("days")),
# textOutput(Final)
)),
tabItem(tabName = "Xrp",
fluidRow(
infoBox("Current XRP Price Change",paste("%",round(XRP/XRP,digits = 4)), icon = icon("bitcoin")),
infoBox("Tomorrow XRP Price Change",paste("%",round(XRP[2]/XRP,digits = 4)), icon = icon("warning"), color = "blue"),
infoBox("Weekly XRP Price Change",paste("%",round(XRP[7]/XRP,digits = 4)), icon = icon("bar-chart-o"), color = "red")
),
fluidRow(
valueBox(paste("$",round(XRP,digits = 2)), "XRP Price Today", icon = icon("hourglass-3")),
valueBox(paste("$",round(XRP[2],digits = 2)), "XRP Price Tomorrow", icon = icon("diamond"), color = "blue"),
valueBox(paste("$",round(XRP[7],digits = 2)), "XRP Price in 1 Week", icon = icon("globe"),color ="red")
),
fluidRow(
box(title = "XRP Projections", status = "primary", solidHeader = T, plotOutput("Xhisto", height = "500px")),
box (title = "Controls for XRP", status = "primary", solidHeader = T,
sliderInput("NUM3","Days for XRP",1,100,50),
dateInput("XRPdate1", "Starting Date", value = Date), dateInput("XRPdate2", "Ending Date", value = Date+6))
##function for Chart
# Final <- difftime(End ,Start , units = c("days")),
# textOutput(Final)
))
)
)
)
)
server = function(input, output){
output$Bhisto <- renderPlot({
plot(BTC)
})
output$Ehisto <- renderPlot({
plot(ETH,breaks = input$NUM2)
})
output$Xhisto <- renderPlot({
plot(XRP,breaks = input$NUM3)
})
}
shinyApp(ui, server)
I am using library(ygdashboard) from here for build a Right Side control bar in Shiny Apps. Which most like AdminLTE.io template.
In AdminLTE.io Right Side Control Bar there is an option,by enabling it the content part will adjust the width and display accordingly.
Can any body help me out here?? My Try:
Mycode:
UI.R
library(shinydashboard)
library(shinyjs)
library(plotly)
library(shinyWidgets)
library(ygdashboard)
library(c3)
library(flexdashboard)
source("helper.R")
dashboardPage( skin = 'green',
dashboardHeader(title=" Test Stand Report",
tags$li(a(img(src = 'logo.jfif',
height = "30px"),
style = "padding-top:10px; padding-bottom:10px;"),
class = "dropdown")),
dashboardSidebar(sidebarMenu(id="tabs",
menuItem("DashBoard", tabName = "dashboard", icon = icon("dashboard", lib = "glyphicon")),
menuItem("Drill Report",icon = icon("link",lib = "glyphicon"),
menuSubItem("Test Stand",tabName = "test_stand",icon = icon("database")),
menuSubItem("Test Code",tabName = "test_code",icon = icon("folder-open",lib = "glyphicon")),
menuSubItem("Product Based",tabName = "product_based",icon = icon("database")),
menuSubItem("Time Shift",tabName = "time_shift",icon = icon("folder-open",lib = "glyphicon"))
)
)
),
dashboardBody(
shinyjs::useShinyjs(),
tabItems(
tabItem(tabName = "dashboard",
fluidRow(
column(3,
gaugeOutput("gauge1",width = "100%", height = "auto"),
uiOutput("infobox_1")
#gaugeOutput("gauge2",width = "100%", height = "auto")
),
column(3,
gaugeOutput("gauge3",width = "100%", height = "auto"),
uiOutput("infobox_2")
#gaugeOutput("gauge4",width = "100%", height = "100px")
),
column(3,
gaugeOutput("gauge5",width = "100%", height = "auto"),
uiOutput("infobox_3")
#gaugeOutput("gauge6",width = "100%", height = "auto")
),
column(3,
gaugeOutput("gauge7",width = "100%", height = "auto"),
uiOutput("infobox_4")
#gaugeOutput("gauge8",width = "100%", height = "auto")
)
),
fluidRow(
)
),
tabItem(tabName = "test_stand",
fluidRow(
column(3,
wellPanel(
uiOutput("test_stand_select")
)
),
column(3,uiOutput("count_test_code")),
column(3,uiOutput("count_vehicle_tested")),
column(3,uiOutput("count_vehicle_failed"))
),
fluidRow(
box(title = "Success Faliure Ratio",solidHeader = TRUE,width = 4,collapsible = TRUE,height = 'auto',status="success",
plotlyOutput("sucess_faliure_pie",height = '250px')
#tableOutput("sucess_faliure_pie")
),
box(title = "Success Faliure rate with Test_Code",solidHeader = TRUE,width = 8,collapsible = TRUE,height = 'auto',status="success",
#tableOutput("test_stand_test_code_rel")
plotlyOutput("test_stand_test_code_rel",height = '250px')
)
)
),
tabItem(tabName = 'test_code',
fluidRow(
)
)
)
),
dashboardFooter(mainText = "My footer", subText = "2018"),
dashboardControlbar()
)
Server.R
library(shiny)
library(shinyjs)
library(RMySQL)
library(DT)
library(devtools)
library(woe)
library(sqldf)
library(plyr)
library(shinyalert)
source("helper.R")
shinyServer(function(input, output,session) {
######################### Date range Selection ################################
output$date_range<-renderUI({
if(input$tabs=="test_stand")
{
dateRangeInput("selected_date_range_test_stand", "Select Time Period:",
start = Sys.Date()-10,
end = Sys.Date(),
max=Sys.Date())
}
else if(input$tabs=="test_code")
{
dateRangeInput("selected_date_range_test_code", "Select Time Period:",
start = Sys.Date()-10,
end = Sys.Date(),
max=Sys.Date())
}
else if(input$tabs=="product_based")
{
dateRangeInput("selected_date_range_product_based", "Select Time Period:",
start = Sys.Date()-10,
end = Sys.Date(),
max=Sys.Date())
}
})
##########################report buttom ################################
output$action_btn<-renderUI({
if(input$tabs=="test_stand")
{
actionBttn("get_data_test_stand","Get Report")
}
else if(input$tabs=="test_code")
{
actionBttn("get_data_test_code","Get Report")
}
else if(input$tabs=="product_based")
{
actionBttn("get_data_product_based","Get Report")
}
})
#########################product group selection##################################
output$pg_list<-renderUI({
if(input$tabs=="test_stand")
{
selectInput("selected_pg_test_stand","Select your Product Group",choices = c("Back"="BHO","SKD"="SKD","ABC"="ABC"))
}
else if(input$tabs=="test_code")
{
selectInput("selected_pg_test_code","Select your Product Group",choices = c("Back"="BHO","SKD"="SKD","ABC"="ABC"))
}
else if(input$tabs=="product_based")
{
selectInput("selected_pg_product_based","Select your Product Group",choices = c("Back"="BHO","SKD"="SKD","ABC"="ABC"))
}
})
#############################top 8 gauge################################
output$gauge1<-renderGauge({
gauge(0.5,
min = 0,
max = 1,
sectors = gaugeSectors(success = c(0.5, 1),
warning = c(0.3, 0.5),
danger = c(0, 0.3)),label = 'Gauge 1')
})
output$infobox_1<-renderInfoBox({
infoBox("Total Test Stand Active",10 * 2,subtitle = "Subtitle", icon = icon("credit-card"),fill = TRUE,color = "yellow")
})
output$gauge3<-renderGauge({
gauge(0.7,
min = 0,
max = 1,
sectors = gaugeSectors(success = c(0.5, 1),
warning = c(0.3, 0.5),
danger = c(0, 0.3)),label = 'Gauge 3')
})
output$infobox_2<-renderInfoBox({
infoBox("Total Test Code Running ",10 * 2,subtitle = "Subtitle" ,icon = shiny::icon("bar-chart"),color = "fuchsia",width = 4,fill = TRUE)
})
output$gauge5<-renderGauge({
gauge(0.6,
min = 0,
max = 1,
sectors = gaugeSectors(success = c(0.5, 1),
warning = c(0.3, 0.5),
danger = c(0, 0.3)),label = 'Gauge 5')
})
output$infobox_3<-renderInfoBox({
infoBox(
"Total Vehicle Tested", "80%",subtitle = "Subtitle", icon = icon("list"),
color = "green", fill = TRUE
)
})
output$gauge7<-renderGauge({
gauge(0.3,
min = 0,
max = 1,
sectors = gaugeSectors(success = c(0.5, 1),
warning = c(0.3, 0.5),
danger = c(0, 0.3)),label = 'Gauge 7')
})
output$infobox_4<-renderInfoBox({
infoBox("Total Vehicle Passed ",10 * 2,subtitle = "Subtitle", icon = icon("check"),fill = TRUE, color = 'orange')
})
#############################test_stand value_box########################
})
Helper.R (from the link)
dashboardControlbar <- function() {
withTags(
div(
id = "right_sidebar",
# Control Sidebar Open
aside(class = "control-sidebar control-sidebar-dark",
# # # # # # # #
#
# Navigation tabs
#
# # # # # # # #
ul(class = "nav nav-tabs nav-justified control-sidebar-tabs",
# first tabs
li(class = "active",
a(href = "#control-sidebar-first-tab", `data-toggle` = "tab",
i(class = "fa fa-sliders")
)
),
# second tabs
li(
a(href = "#control-sidebar-second-tab", `data-toggle` = "tab",
i(class = "fa fa-search")
)
),
# third tab
li(
a(href = "#control-sidebar-third-tab", `data-toggle` = "tab",
i(class = "fa fa-paint-brush")
)
)
),
# # # # # # # #
#
# Tab Panels
#
# # # # # # # #
div(class = "tab-content",
#########################
# First tab content #
#########################
div(class = "tab-pane active", id = "control-sidebar-first-tab",
h3(class = "control-sidebar-heading", "Controller"),
# write elements here
uiOutput("date_range"),
#textOutput("date_validate"),
uiOutput("pg_list"),
uiOutput("action_btn")
#actionBttn("get_data","Get Report")
),
#########################
# Second tab content #
#########################
div(class = "tab-pane", id = "control-sidebar-second-tab",
h3(class = "control-sidebar-heading", "Search"),
# write other elements here
selectInput("selected_search_topic","Select Content Type to Seacrh",choices = c("Test Stand","Test Code","Product")),
searchInput("searchtext","Enter your Search Topic Here", placeholder = "A placeholder",btnSearch = icon("search"),btnReset = icon("remove"))
),
#########################
# Third tab content #
#########################
div(class = "tab-pane", id = "control-sidebar-third-tab",
# third tab elements here
radioButtons("dist", "Distribution type:",
c("Normal" = "norm",
"Uniform" = "unif",
"Log-normal" = "lnorm",
"Exponential" = "exp")
)
)
)
),
# control-sidebar
# Add the sidebar background. This div must be placed
# immediately after the control sidebar
div(class = "control-sidebar-bg", "")
)
)
}
I am doing some timeseries analysis and have created a shiny app where when the app starts sample timeseries data is uploaded or the user can upload csv dataset from his local directory....
Sample Dataset:
df
month passengers
1 01-01-2000 2072798
2 01-02-2000 2118150
3 01-03-2000 2384907
4 01-04-2000 2260620
5 01-05-2000 2386165
6 01-06-2000 2635018
7 01-07-2000 2788843
8 01-08-2000 2942082
9 01-09-2000 2477000
10 01-10-2000 2527969
11 01-11-2000 2161170
12 01-12-2000 2175314
13 01-01-2001 2307525
14 01-02-2001 2196415
15 01-03-2001 2545863
library(signal)
library(shiny)
library(AnomalyDetection) #devtools::install_github("twitter/AnomalyDetection")
library(ggplot2)
# Define UI for application that draws a histogram
library(shinydashboard)
library(shinycssloaders)
library(googleVis)
shinyUI(dashboardPage(skin = "green",
dashboardHeader(title = "Anomaly Detection in Time series",
titleWidth = 350),
dashboardSidebar(
sidebarUserPanel("Nishant Upadhyay",
image = "nishantcofyshop.jpg"
),
sidebarMenu(
menuItem("Data", tabName = "data", icon = icon("database")),
menuItem("Filters", tabName = "filter", icon = icon("filter")),
menuItem("Anomalies", tabName = "anomaly", icon = icon("check")),
#menuItem("Save Data", tabName = "save", icon = icon("save"))
menuItem("About The App", tabName = "Help", icon = icon("info-circle"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "data",
fluidRow(
box(
title = "Data scatter Chart",
status = "primary",
solidHeader = T,
collapsible = T,
width = 12,
shinycssloaders::withSpinner(htmlOutput("dataChart"),type = getOption("spinner.type", default = 8),color = "red")
)
),
fluidRow(
box(
radioButtons(
"data_input","",
choices = list("Load sample data" = 1,
"Upload csv file" = 2
)
),
conditionalPanel(
condition = "input.data_input=='1'",
h5("Sample dataset of Lebron James basketball shots over the years")
),
conditionalPanel(
condition = "input.data_input=='2'",
fileInput('file1', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv'
)),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),','),
radioButtons('quote', 'Quote',
c('None'='',
'Double Quote'='"',
'Single Quote'="'"),
'')
),
title = "Select Dataset",
status = "info",
solidHeader = T,
collapsible = T
),
box(
title = "Data",
status = "info",
solidHeader = T,
collapsible = T,
shinycssloaders::withSpinner(htmlOutput('contents'),type = getOption("spinner.type", default = 8),color = "red")
)# end of box
)## end of Fluid row
), ## end of tab item
tabItem(
tabName = "filter",
fluidRow(
box(
title = "Data Chart",
status = "primary",
solidHeader = T,
collapsible = T,
width = 12,
shinycssloaders::withSpinner(htmlOutput('dataChartFiltered'),type = getOption("spinner.type", default = 8),color = "red")
)
),
fluidRow(
box(
title = "Filters",
status = "info",
solidHeader = T,
collapsible = T,
width = 4,
radioButtons("filt", NULL,
c("None" = "none",
"Butterworth" = "butt",
"Type-II Chebyshev" = "cheby2")),
submitButton("Filter")
),
box(
title = "Butterworth",
status = "info",
solidHeader = T,
collapsible = T,
width = 4,
textInput("buttern", label = "Filter Order", value = "3"),
textInput("butterf", label = "Critical Frequencies", value = "0.1"),
radioButtons("buttert", "Type",
c("Low-Pass" = "low",
"High-Pass" = "high"))
),
box(
title = "Chebyshev",
status = "info",
solidHeader = T,
collapsible = T,
width = 4,
textInput("chebyn", label = "Filter Order", value = "5"),
textInput("chebyd", label = "dB of Pass Band", value = "20"),
textInput("chebyf", label = "Critical Frequencies", value = "0.2"),
radioButtons("chebyt", "Type",
c("Low-Pass" = "low",
"High-Pass" = "high"))
)
)
)
) ## end of tab items
) ## end of Dashboard
)
)
shinyServer(function(input, output){
dataframe<-reactive({
if (input$data_input == 1) {
tab <- read.csv("df.csv",header = T,stringsAsFactors = F)
} else if (input$data_input == 2) {
inFile <- input$file1
if (is.null(inFile))
return(data.frame(x = "Select your datafile"))
tab = read.csv(inFile$datapath, header = input$header,
sep = input$sep, quote = input$quote)
}
tt <- tryCatch(as.POSIXct(tab[,1]),error=function(e) e, warning=function(w) w)
if (is(tt,"warning") | is(tt,"error")) {
tab$Old = tab[,1]
tab[,1] = as.POSIXct(1:nrow(tab), origin = Sys.time())
} else {
tab[,1] = as.POSIXct(tab[,1])
}
tab
})
output$dataChart <- renderGvis({
if (!is.null(dataframe()))
gvisLineChart(dataframe()[,c(1,2)], xvar = colnames(dataframe())[1], yvar = colnames(dataframe())[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
})
output$contents <- renderGvis({
if (!is.null(dataframe()))
gvisTable(dataframe(),
options = list(page='enable'))
})
output$dataChartFiltered <- renderGvis({
if (input$filt == "none") {
return(NULL)
} else if (input$filt == "butt") {
bf <- butter(as.numeric(input$buttern), as.numeric(input$butterf), type = input$buttert)
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(bf, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
} else if (input$filt == "cheby2") {
ch <- cheby2(as.numeric(input$chebyn), as.numeric(input$chebyd),
as.numeric(input$chebyf), type = input$chebyt)
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(ch, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
}
})
})
The problem i am facing is that once the shiny app is executed , the sample data is loaded properly as the this data is placed in the app folder in the directory (one can use R inbuilt data set or use the data i gave in the start) and subsequently all steps gets executed properly.
But if i want to upload some other csv file from local directory, the upload button selection does not get activated even after selecting it.But,in fact, if one goes to the second menu item in the sidebar panel i.e. filter tab and clicks on the filter button (under Filters box ) and then if i go back to Data menu in the sidebar panel again, i can see that now my upload csv file button has got activated and now i can browse the csv file in local directory and upload the same into the app and now everything works fine.
It seems somewhere the condition that makes the upload file button is not getting active initially when the app opens....
Need help to sort out the issue...Sorry for posting large chunk of code....
conditionalPanel and submitButton do not work well together. Replace your submitButton("Filter") with actionButton("Filter", "").
EDIT:
As per the comment, for the plot to be generated only after the actionButton is clicked you can put output$dataChartFiltered inside observeEvent of Filter with isolate for `input objects as follows:
observeEvent(input$Filter,{
output$dataChartFiltered <- renderGvis({
if (isolate(input$filt) == "none") {
return(NULL)
} else if (isolate(input$filt) == "butt") {
bf <- butter(as.numeric(isolate(input$buttern)), as.numeric(isolate(input$butterf)), type = isolate(input$buttert))
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(bf, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
} else if (isolate(input$filt) == "cheby2") {
ch <- cheby2(as.numeric(isolate(input$chebyn)), as.numeric(isolate(input$chebyd)),
as.numeric(isolate(input$chebyf)), type = isolate(input$chebyt))
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(ch, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
}
})
})