If you please run the script, it gives you a basic Sankey Chart in R and plotly and a data table besides. Also, there are three infoBoxes on top. When I click on the Sankey lines in the plot, I see the value in the data table using plotly_click. I want a functionality when I click on any Sankey Line, it picks "pointNumber" Column value in the data table and then multiplies by 2 and put in first infobox, by 3 in second infobox, and multiply by 4 in third infobox as in the snap attached. Thanks and please help.
## app.R ##
library(shiny)
library(shinydashboard)
library(devtools)
library(ggplot2)
library(plotly)
library(proto)
library(RColorBrewer)
library(gapminder)
library(stringr)
library(broom)
library(mnormt)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "Multiple hover"),
dashboardSidebar(
width = 0
),
dashboardBody(
infoBox("Multiply by 2", 2 * 2, icon = icon("credit-card")),
infoBox("Multiply by 3", 2 * 3, icon = icon("credit-card")),
infoBox("Multiply by 4", 2 * 4, icon = icon("credit-card")),
tags$br(),
box(title = "Sankey Chart", status = "primary",height = "455" ,solidHeader =
T,
plotlyOutput("sankey_plot")),
box( title = "Case Summary", status = "primary", height = "455",solidHeader
= T,
dataTableOutput("sankey_table"))
)
)
server <- function(input, output)
{
output$sankey_plot <- renderPlotly({
trace1 <- list(
domain = list(
x = c(0, 1),
y = c(0, 1)
),
link = list(
label = c("Case1", "Case2", "Case3", "Case4", "Case5", "Case6",
"Case7"),
source = c(0, 1, 2, 3, 4, 5, 6, 7),
target = c(11, 12, 7, 10, 13, 9, 8),
value = c(5, 6, 2, 4, 10, 6, 2)
),
node = list(label = c("R1", "R2", "R3","R4","R5","R6","R7","Blood
Test","Check Out","Discuss Results",
"MRI Scan", "Registration", "Triage and Assessment",
"X-RAY")),
type = "sankey"
)
data <- list(trace1)
p <- plot_ly()
p <- add_trace(p, domain=trace1$domain, link=trace1$link,
node=trace1$node, type=trace1$type)
p
})
output$sankey_table <- renderDataTable({
d <- event_data("plotly_click")
if(is.null(d))
{
print("Hello, Please hover to see the result" )
} else
d
})
}
shinyApp(ui, server)
Considering event_data() outputs a dataframe, the below code access that particular value pointNumber and renders dynamic UI.
Code:
## app.R ##
library(shiny)
library(shinydashboard)
library(devtools)
library(ggplot2)
library(plotly)
library(proto)
library(RColorBrewer)
library(gapminder)
library(stringr)
library(broom)
library(mnormt)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "Multiple hover"),
dashboardSidebar(
width = 0
),
dashboardBody(
uiOutput('box1'),
tags$br(),
box(title = "Sankey Chart", status = "primary",height = "455" ,solidHeader =
T,
plotlyOutput("sankey_plot")),
box( title = "Case Summary", status = "primary", height = "455",solidHeader
= T,
dataTableOutput("sankey_table"))
)
)
server <- function(input, output)
{
output$sankey_plot <- renderPlotly({
trace1 <- list(
domain = list(
x = c(0, 1),
y = c(0, 1)
),
link = list(
label = c("Case1", "Case2", "Case3", "Case4", "Case5", "Case6",
"Case7"),
source = c(0, 1, 2, 3, 4, 5, 6, 7),
target = c(11, 12, 7, 10, 13, 9, 8),
value = c(5, 6, 2, 4, 10, 6, 2)
),
node = list(label = c("R1", "R2", "R3","R4","R5","R6","R7","Blood
Test","Check Out","Discuss Results",
"MRI Scan", "Registration", "Triage and Assessment",
"X-RAY")),
type = "sankey"
)
data <- list(trace1)
p <- plot_ly()
p <- add_trace(p, domain=trace1$domain, link=trace1$link,
node=trace1$node, type=trace1$type)
p
})
output$sankey_table <- renderDataTable({
d <- event_data("plotly_click")
if(is.null(d))
{
print("Hello, Please hover to see the result" )
} else
d
})
output$box1 <- renderUI({
tagList(
infoBox("Multiply by 2", event_data("plotly_click")$pointNumber * 2, icon = icon("credit-card")),
infoBox("Multiply by 3", event_data("plotly_click")$pointNumber * 3, icon = icon("credit-card")),
infoBox("Multiply by 4", event_data("plotly_click")$pointNumber * 4, icon = icon("credit-card"))
)
})
}
shinyApp(ui, server)
Screenshot:
Related
I have a table being display in a shiny app. I want to format the tables based on the values and color it accordingly. I have seen the formattable area coloring where based on the range of the values it defines the breaks and then color gradients are generated which are applied to the table. What I want to do is allow the user to fill the min and max value and depending on it the values in the table will be colored. So if the values range from 1-20 and if the user inputs are 5 and 15 , values below 5 and above 15 shouldnt have any color gradients applied to them. Below is the code of how I am doing currently using formatable area formatting.
library(shiny)
library(shinyWidgets)
library(shinydashboard)
library(DT)
sidebar <- dashboardSidebar(
sidebarMenu(id = "tab",
menuItem("1", tabName = "1")
)
)
body <- ## Body content
dashboardBody(box(width = 12,fluidRow(
fluidRow( column(
width = 3, textInput("text1", label = h5("Min"), value = "Enter min")),
column(
width = 3, textInput("text2", label = h5("Max"), value = "Enter max"))),
DT::dataTableOutput("op")
)))
ui <- dashboardPage(dashboardHeader(title = "Scorecard"),
sidebar,
body)
# Define the server code
server <- function(input, output,session) {
df <- data.frame(month = c("mazda 3", "mazda cx5", "mazda 6","mazda miata","honda civic","honda accord"),
april = c(.1,.2,.3,.3,.4,.5),
may = c(.3,.4,.5,.2,.1,.5),
june = c(.2,.1,.5,.1,.2,.3))
brks <- reactive({ quantile(df$april, probs = seq(.05, .95, .05), na.rm = TRUE)})
clrs <- reactive({ round(seq(255, 175, length.out = length(brks()) + 1), 0) %>%
{paste0("rgb(",.,",", ., ",255 )")}})
df_format<- reactive ({datatable(df,options = list(searching = FALSE,pageLength = 15, lengthChange = FALSE))%>%
formatStyle(names(df),backgroundColor = styleInterval(brks(), clrs()))})
output$op <-renderDataTable({
df_format()
})
}
shinyApp(ui = ui, server = server)
Here is your working code.
You must use that input minimal and maximal value as limits for your sequence (I just change it to range - is easier for user to put a range like that)
Then you generate sequence - according your notation - brks() - in my case I use length.out of 10 but you can put as many breaks as you want or dynamically.
Then generate on
number of colors - 1
and in the end in styleInterval() for background add limits of white - or any other color you want.
library(shiny)
library(shinyWidgets)
library(shinydashboard)
library(DT)
sidebar <- dashboardSidebar(
sidebarMenu(id = "tab",
menuItem("1", tabName = "1")
)
)
body <- ## Body content
dashboardBody(box(width = 12,fluidRow(
fluidRow(column(
width = 3,
sliderInput("range_value",
label = h3("Put a range value"),
min = 0,
max = 100,
value = c(5, 15)
)
)
),
DT::dataTableOutput("op")
)))
ui <- dashboardPage(dashboardHeader(title = "Scorecard"),
sidebar,
body)
# Define the server code
server <- function(input, output,session) {
df <- data.frame(month = c("mazda 3", "mazda cx5", "mazda 6","mazda miata","honda
civic","honda accord"),
april = c(9, 8, 11,14,16,1),
may = c(3,4,15,12,11, 19),
june = c(2,11,9,7,14,1))
brks <- reactive({
seq(input$range_value[1], input$range_value[2], length.out = 10)
})
clrs <- reactive({ round(seq(255, 175, length.out = length(brks()) - 1), 0) %>%
{paste0("rgb(",.,",", ., ",255)")}})
df_format<- reactive ({datatable(df,options = list(searching = FALSE, pageLength = 15, lengthChange = FALSE)) %>%
formatStyle(names(df),
backgroundColor = styleInterval(c(brks()), c('white', clrs() ,'white'))
)
})
output$op <-renderDataTable({
df_format()
})
}
shinyApp(ui = ui, server = server)
As per object, I get a very small plot in Firefox when using sankeyNetwork() from networkd3 in shiny but not in Chrome or RStudio.
I have not included any CSS or JS in the script - the code below produces this result for me.
Is there any CSS property I have missed?
I am using R 3.4.1, shiny 1.1.0, networkD3 0.4 and Firefox 52.9.0.
Firefox:
Chrome:
library(shiny)
library(magrittr)
library(shinydashboard)
library(networkD3)
labels = as.character(1:9)
ui <- tagList(
dashboardPage(
dashboardHeader(
title = "appName"
),
##### dasboardSidebar #####
dashboardSidebar(
sidebarMenu(
id = "sidebar",
menuItem("plots",
tabName = "sPlots")
)
),
##### dashboardBody #####
dashboardBody(
tabItems(
##### tab #####
tabItem(
tabName = "sPlots",
tabsetPanel(
tabPanel(
"Sankey plot",
fluidRow(
box(title = "title",
solidHeader = TRUE, collapsible = TRUE, status = "primary",
sankeyNetworkOutput("sankeyHSM1")
)
)
)
)
)
)
)
)
)
server <- function(input, output, session) {
HSM = matrix(rep(c(10000, 700, 10000-700, 200, 500, 50, 20, 10, 2,40,10,10,10,10),4),ncol = 4)
sankeyHSMNetworkFun = function(x,ndx) {
nodes = data.frame("name" = factor(labels, levels = labels),
"group" = as.character(c(1,2,2,3,3,4,4,4,4)))
links = as.data.frame(matrix(byrow=T,ncol=3,c(
0, 1, NA,
0, 2, NA,
1, 3, NA,
1, 4, NA,
3, 5, NA,
3, 6, NA,
3, 7, NA,
3, 8, NA
)))
links[,3] = HSM[2:(nrow(links)+1),] %>% {rowSums(.[,(ndx-1)*2+c(1,2)])}
names(links) = c("source","target","value")
sankeyNetwork(Links = links, Nodes = nodes, Source = "source", Target = "target", Value = "value", NodeID = "name",NodeGroup = "group",
fontSize=12,sinksRight = FALSE)
}
output$sankeyHSM1 = renderSankeyNetwork({
sankeyHSMNetworkFun(values$HSM,1)
})
}
# Run the application
shinyApp(ui = ui, server = server)
------------------ EDIT --------------------
Thanks to #CJYetman for indicating onRender() as a possible solution - however this fails when there are two plots generated side by side as in the MRE below (note in addition to the second sankey plot I have also added javascript code to re-draw the figures when the window size changes as the plot does not appear to do it automatically).
library(shiny)
library(magrittr)
library(shinydashboard)
library(networkD3)
library(htmlwidgets)
labels = as.character(1:9)
ui <- tagList(
tags$head(
tags$script('
var dimension = [0, 0];
$(document).on("shiny:connected", function(e) {
dimension[0] = window.innerWidth;
dimension[1] = window.innerHeight;
Shiny.onInputChange("dimension", dimension);
});
$(window).resize(function(e) {
dimension[0] = window.innerWidth;
dimension[1] = window.innerHeight;
Shiny.onInputChange("dimension", dimension);
});
')
),
dashboardPage(
dashboardHeader(
title = "appName"
),
##### dasboardSidebar #####
dashboardSidebar(
sidebarMenu(
id = "sidebar",
menuItem("plots",
tabName = "sPlots")
)
),
##### dashboardBody #####
dashboardBody(
tabItems(
##### tab #####
tabItem(
tabName = "sPlots",
tabsetPanel(
tabPanel(
"Sankey plot",
fluidRow(
box(title = "title",
solidHeader = TRUE, collapsible = TRUE, status = "primary",
sankeyNetworkOutput("sankeyHSM1")
),
box(title = "plot2",
solidHeader = TRUE, collapsible = TRUE, status = "primary",
sankeyNetworkOutput("sankeyHSM2"))
)
)
)
)
)
)
)
)
server <- function(input, output, session) {
HSM = matrix(rep(c(10000, 700, 10000-700, 200, 500, 50, 20, 10, 2,40,10,10,10,10),4),ncol = 4)
sankeyHSMNetworkFun = function(x,ndx) {
nodes = data.frame("name" = factor(labels, levels = labels),
"group" = as.character(c(1,2,2,3,3,4,4,4,4)))
links = as.data.frame(matrix(byrow=T,ncol=3,c(
0, 1, NA,
0, 2, NA,
1, 3, NA,
1, 4, NA,
3, 5, NA,
3, 6, NA,
3, 7, NA,
3, 8, NA
)))
links[,3] = HSM[2:(nrow(links)+1),] %>% {rowSums(.[,(ndx-1)*2+c(1,2)])}
names(links) = c("source","target","value")
sankeyNetwork(Links = links, Nodes = nodes, Source = "source", Target = "target", Value = "value", NodeID = "name",NodeGroup = "group",
fontSize=12,sinksRight = FALSE)
}
output$sankeyHSM1 = renderSankeyNetwork({
req(input$dimension)
sankeyHSMNetworkFun(values$HSM,1) %>%
onRender('document.getElementsByTagName("svg")[0].setAttribute("viewBox", "")')
})
output$sankeyHSM2 = renderSankeyNetwork({
req(input$dimension)
sankeyHSMNetworkFun(values$HSM,2) %>%
onRender('document.getElementsByTagName("svg")[0].setAttribute("viewBox", "")')
})
}
# Run the application
shinyApp(ui = ui, server = server)
------------------ EDIT2 --------------------
Second problem above solved - either by referring to the second svg item on the page as per #CJYetman's comment below using document.getElementsByTagName("svg")[1].setAttribute("viewBox",""), or by going into the objects themselves selecting their first svg element with document.getElementById("sankeyHSM2").getElementsByTagName("svg")[0].setAttribute("viewBox","").
This seems to be the result of Firefox reacting to the viewbox svg property differently than other browsers. It might be worthwhile to submit this as an issue here https://github.com/christophergandrud/networkD3/issues
In the meantime, you could work around this by resetting the viewbox attribute using some JavaScript and htmlwidgets::onRender(). Here's an example using a minimized version of your example. (Resetting the viewbox attribute may have other consequences)
library(htmlwidgets)
library(networkD3)
library(magrittr)
nodes = data.frame("name" = factor(as.character(1:9)),
"group" = as.character(c(1,2,2,3,3,4,4,4,4)))
links = as.data.frame(matrix(byrow = T, ncol = 3, c(
0, 1, 1400,
0, 2, 18600,
1, 3, 400,
1, 4, 1000,
3, 5, 100,
3, 6, 40,
3, 7, 20,
3, 8, 4
)))
names(links) = c("source","target","value")
sn <- sankeyNetwork(Links = links, Nodes = nodes, Source = "source",
Target = "target", Value = "value", NodeID = "name",
NodeGroup = "group", fontSize = 12, sinksRight = FALSE)
htmlwidgets::onRender(sn, 'document.getElementsByTagName("svg")[0].setAttribute("viewBox", "")')
UPDATE (2019.10.26)
This is probably a safer implementation of removing the viewBox...
htmlwidgets::onRender(sn, 'function(el) { el.getElementsByTagName("svg")[0].removeAttribute("viewBox") }')
UPDATE 2020.04.02
My currently preferred method to do this is to use htmlwidgets::onRender to target specifically the SVG contained by the passed htmlwidget, like this...
onRender(sn, 'function(el) { el.querySelector("svg").removeAttribute("viewBox") }')
That can then be done specifically to as many htmlwidgets on your page as necessary, for instance...
onRender(sn, 'function(el) { el.querySelector("svg").removeAttribute("viewBox") }')
onRender(sn2, 'function(el) { el.querySelector("svg").removeAttribute("viewBox") }')
This is related to another post I have, concerning adding a new fluidRow (conainting plot + selectInput) in my shinyDashboard app.
When I run the code below, I'm receiving the following
Error in if (inline) { : argument is not interpretable as logical
I've tried to tinker with the way the code is written, e.g. remove commas, but I've not been able to find a way to get rid of the error. What's more, I think it's one of the causes of not being able to generate an additional fluidrow.
I have a feeling its got something to do with my input controls, but no idea what!
Any help would be appreciated.
ui.r
ui <- dashboardPage(
skin = "red",
dashboardHeader(title = "iReport",
titleWidth = 500),
dashboardSidebar(),
dashboardBody(
tabItems(
# Tab for Dashboard
tabItem(tabName = "Dashboard"),
# Tab for Survey Analytics
tabItem(tabName = "Survey"),
#Tab for Enquiry Analytics
tabItem(tabName = "Enquiries"),
#Tab for Web Analytics
tabItem(tabName = "Metrics"),
#Tab for Twitter Analytics
tabItem(tabName = "Twitter")
),
# Row 1 objects
fluidRow(
# Value boxes
valueBox(
479,
"Total No. of Enquiries",
color = "green",
icon = icon("commenting")
),
valueBox(
1.7,
"Average response time",
color = "blue",
icon = icon("exchange")
),
valueBox(
"98%",
"Percentage satisfied customers",
color = "orange",
icon = icon("thumbs-up")
)
),
# Row 2 objects
fluidRow(box(
width = 12, plotlyOutput("Time_Ser", height = "400px")
)),
# Row 3 objects
fluidRow(
# Data visualisations 1
box(width = 5, plotlyOutput("Enq_Num", height = "500px")),
box(
width = 2,
h2("Control panel"),
dateRangeInput(
"date",
"Date:",
label = h4("Choose a time frame"),
start = "2017-05-02",
end = "2017-07-30",
min = "2017-05-02",
max = "2017-06-30",
startview = "2017-06-30"
),
selectInput(
"select",
"Select",
label = h4("Select a month"),
choices = c("May", "June")
),
radioButtons(
"area",
"Area",
label = h4("Response Time by Team"),
choices = list("PEU", "DAU", "MSU", "PRO", "MISC"),
selected = "PEU"
)),
box(width = 5, plotlyOutput("Response", height = "500px"))),
#Row 4 Objects
fluidRow(# Data visualisations 2
box(width = 5, plotlyOutput("Enq_Outcome")),
box(
width = 2,
selectInput(
"outcome",
"Outcome",
label = h4("Enquiry outcomes by output area"),
choices = list("Link", "Clarified", "CM", "Unavailable", "Referred")
)))))
server.r
server <- function(input, output) {
# Reactive date input for Tim_Ser
Time2 <- Time
reactiveTime <- reactive({
Time2 %>% filter(Date.received >= input$date[1] &
Date.received < input$date[2])})
# DATA
Numbers <-
data.frame(
May = c(73, 26, 23, 10, 23),
June = c(144, 28, 21, 20, 33),
areas = c("PEU", "MIG", "DAU", "MISC", "PRO")
)
Time <- CusTible %>% group_by(Date.received) %>% tally(sort = TRUE)
Time = Time[order(Time$Date.received), ]
Respond <-
data.frame(
DAU = c(32, 14, 8),
MIG = c(51, 7, 4),
MISC = c(42, 41, 3),
PEU = c(135, 16, 18),
PRO = c(32, 15, 2),
Days = c("1-2 Days", "3-4 Days", "5+ Days")
)
rownames(Respond) <- c("1-2 Days", "3-4 Days", "5+ Days")
Outcome <-
data.frame(
Area = c("DAU", "PEU", "PRO", "MSU", "MISC"),
CLAR = c(5, 23, 2, 2, 13),
LINK = c(45, 4, 23, 24, 18),
UNAV = c(1, 13, 15, 11, 12),
CM = c(8, 15, 3, 10, 2),
REF = c(26, 24, 11, 7, 12)
)
# OUTPUTS
output$Time_Ser <- renderPlotly({
Time_Ser <-
plot_ly(reactiveTime(),
x = Date.received,
y = n,
mode = "lines") %>%
layout(title = "Q3. Enquiries over Time")
})
output$Enq_Num <- renderPlotly({
selector <- switch(input$select,
"May" = Numbers$May,
"June" = Numbers$June)
Enq_Num <- plot_ly(
Numbers,
x = areas,
y = selector,
type = "bar",
color = areas
) %>%
layout(
title = "Q3. Enquiries by Output Team by Month",
xaxis = list(title = "Output Team", showgrid = F),
yaxis = list(title = "No. Enquiries")
)
})
output$Response <- renderPlotly({
if (is.null(input$area))
return()
area.select <- switch(
input$area,
"PEU" = Respond$PEU,
"DAU" = Respond$DAU,
"MSU" = Respond$MIG,
"PRO" = Respond$PRO,
"MISC" = Respond$MISC
)
Response <- plot_ly(
Respond,
labels = Days,
values = area.select,
type = "pie",
rotation = 180,
direction = "clockwise",
hole = 0.6
) %>%
layout(title = "Q3. Response Time")
})
output$Enq_Outcome <- renderPlotly({
enq.outcome <- switch(
input$outcome,
"Clarified" = Outcome$CLAR,
"Link" = Outcome$LINK,
"CM" = Outcome$CM,
"Unavailable" = Outcome$UNAV,
"Referred" = Outcome$REF
)
Enq_Outcome <- renderPlotly(
Outcome,
y = Area,
x = enq.outcome,
type = "bar",
colour = Area
)
})
}
shinyApp(ui, server)
So after much persistence and a lot of help from the expert,
I find all my problems come down to the radioButton() input selector:
I replace
radioButtons(
"area",
"Area",
label = h4("Response Time by Team"),
choices = list("PEU", "DAU", "MSU", "PRO", "MISC"),
selected = "PEU"
)),
with
selectInput(
"area",
"Area",
label = h4("Response Time by Team"),
choices = list("PEU", "DAU", "MSU", "PRO", "MISC"),
)),
And the code works perfectly fine, the error message disappears and the new plot and fluidRow are integrated into the Dashboard.
Got a few really tedious issue with Shiny Dashboard.
So, I've got three main plots and a input control panel, which span 2 fluidRows. I want to add another plot (Enq_Outcome) in a separate fluidRow, but having troubles displaying it in the viewer when loading the app.
In fact, there doesn't actually appear to be any problems with the code (at least R is not flagging it up when I run the code) and the rest of the app appears to load properly without any error messages (most of it anyway). So I'm not entirely sure why my new plot (Enq_Outcome) is not appearing.
In addition to this, two of my plots (Time_Ser) and (Response) don't initiate the default plot when loading the app, e.g. so the selected = " " argument doesn't appear to work for my radioButtons and dateRangeInput inputs.
Any help with this would be great as it's been puzzling me for ages.
ui.r
ui <- dashboardPage(
skin = "red",
dashboardHeader(title = "iReport",
titleWidth = 500),
dashboardSidebar(),
dashboardBody(
tabItems(
# Tab for Dashboard
tabItem(tabName = "Dashboard"),
# Tab for Survey Analytics
tabItem(tabName = "Survey"),
#Tab for Enquiry Analytics
tabItem(tabName = "Enquiries"),
#Tab for Web Analytics
tabItem(tabName = "Metrics"),
#Tab for Twitter Analytics
tabItem(tabName = "Twitter")
),
# Row 1 objects
fluidRow(
# Value boxes
valueBox(
479,
"Total No. of Enquiries",
color = "green",
icon = icon("commenting")
),
valueBox(
1.7,
"Average response time",
color = "blue",
icon = icon("exchange")
),
valueBox(
"98%",
"Percentage satisfied customers",
color = "orange",
icon = icon("thumbs-up")
)
),
# Row 2 objects
fluidRow(box(
width = 12, plotlyOutput("Time_Ser", height = "400px")
)),
# Row 3 objects
fluidRow(
# Data visualisations 1
box(width = 5, plotlyOutput("Enq_Num", height = "500px")),
box(
width = 2,
h2("Control panel"),
dateRangeInput(
"date",
"Date:",
label = h4("Choose a time frame"),
start = "2017-05-02",
end = "2017-07-30",
min = "2017-05-02",
max = "2017-06-30",
startview = "2017-06-30"
),
selectInput(
"select",
"Select",
label = h4("Select a month"),
choices = c("May", "June")
),
radioButtons(
"area",
"Area",
label = h4("Response Time by Team"),
choices = list("PEU", "DAU", "MSU", "PRO", "MISC"),
selected = "PEU"
)),
box(width = 5, plotlyOutput("Response", height = "500px"))),
#Row 4 Objects
fluidRow(# Data visualisations 2
box(width = 5, plotlyOutput("Enq_Outcome")),
box(
width = 2,
selectInput(
"outcome",
"Outcome",
label = h4("Enquiry outcomes by output area"),
choices = list("Link", "Clarified", "CM", "Unavailable", "Referred")
)))))
server.r
server <- function(input, output) {
# Reactive date input for Tim_Ser
Time2 <- Time
reactiveTime <- reactive({
Time2 %>% filter(Date.received >= input$date[1] &
Date.received < input$date[2])})
# DATA
Numbers <-
data.frame(
May = c(73, 26, 23, 10, 23),
June = c(144, 28, 21, 20, 33),
areas = c("PEU", "MIG", "DAU", "MISC", "PRO")
)
Time <- data.frame(date = c("2017-05-02","2017-05-03","2017-05-04", "2017-05-05","2017-05-07"), n = c(14,11,7,12,14))
Respond <-
data.frame(
DAU = c(32, 14, 8),
MIG = c(51, 7, 4),
MISC = c(42, 41, 3),
PEU = c(135, 16, 18),
PRO = c(32, 15, 2),
Days = c("1-2 Days", "3-4 Days", "5+ Days")
)
rownames(Respond) <- c("1-2 Days", "3-4 Days", "5+ Days")
Outcome <-
data.frame(
Area = c("DAU", "PEU", "PRO", "MSU", "MISC"),
CLAR = c(5, 23, 2, 2, 13),
LINK = c(45, 4, 23, 24, 18),
UNAV = c(1, 13, 15, 11, 12),
CM = c(8, 15, 3, 10, 2),
REF = c(26, 24, 11, 7, 12)
)
# OUTPUTS
output$Time_Ser <- renderPlotly({
Time_Ser <-
plot_ly(reactiveTime(),
x = Date.received,
y = n,
mode = "lines") %>%
layout(title = "Q3. Enquiries over Time")
})
output$Enq_Num <- renderPlotly({
selector <- switch(input$select,
"May" = Numbers$May,
"June" = Numbers$June)
Enq_Num <- plot_ly(
Numbers,
x = areas,
y = selector,
type = "bar",
color = areas
) %>%
layout(
title = "Q3. Enquiries by Output Team by Month",
xaxis = list(title = "Output Team", showgrid = F),
yaxis = list(title = "No. Enquiries")
)
})
output$Response <- renderPlotly({
if (is.null(input$area))
return()
area.select <- switch(
input$area,
"PEU" = Respond$PEU,
"DAU" = Respond$DAU,
"MSU" = Respond$MIG,
"PRO" = Respond$PRO,
"MISC" = Respond$MISC
)
Response <- plot_ly(
Respond,
labels = Days,
values = area.select,
type = "pie",
rotation = 180,
direction = "clockwise",
hole = 0.6
) %>%
layout(title = "Q3. Response Time")
})
output$Enq_Outcome <- renderPlotly({
enq.outcome <- switch(
input$outcome,
"Clarified" = Outcome$CLAR,
"Link" = Outcome$LINK,
"CM" = Outcome$CM,
"Unavailable" = Outcome$UNAV,
"Referred" = Outcome$REF
)
Enq_Outcome <- renderPlotly(
Outcome,
y = Area,
x = enq.outcome,
type = "bar",
colour = Area
)
})
}
Run App
shinyApp(ui, server)
I am trying to create a simple shiny app for plotting histogram inside rstudio running on Amazon ec2 for my result data stored as .RData file. I have double checked everything. It looks fine.
I have also checked the data types: all are numeric.
My codes:
ui.R
# shiny plots on top_docs data
library(shiny)
shinyUI(fluidPage(
# Header title
titlePanel(title = h4("Top doctors plots - a histograms", align = "center")),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput(
selectInput("var", "1, Select the variables from top doc summary file",
choices =c( "service_total" = 1,
"ben_total" = 2,
"payment" = 3,
"charged" = 4,
"allowed" = 5,
"unique_services_per_patient" = 6,
"duplicates_per_service" = 7,
"services_per_patient" = 8), selected= 1 ),
br(),
sliderInput("bins", "2, Select the number of BINs for histogram", min = 5, max = 40, value=20),
br(),
radioButtons("color", "3, Select the color of histogram", choices =c("Green", "Red", "Yellow"), selected= "Green")
)),
# Show a plot of the generated distribution
mainPanel(
plotOutput("myhist")
)
))
)
server.R
`library(ggplot2)
library(shiny)
options(shiny.error=browser)
load("/******/top_docs.RData", envir=.GlobalEnv)
shinyServer(function(input, output) {
output$myhist <- renderPlot({
# generate var based on input$var from ui.R
col <- as.numeric(input$var)
hist(top_docs[,col], breaks = seq(0, max(top_docs[,col], l = input$bins+1), col=input$color, main="Histogram of Top docs", xlab=names(top_docs[col])))
})
})
`
Found it... All the sidebarPanel content was inside a sliderInput function that gives error
top_docs = data.frame( service_total = sample(1:100000, 40, replace=T),
ben_total = sample(1:100000, 40, replace=T)
, payment = sample(1:100000, 40, replace=T), charged = sample(1:100000, 40, replace=T)
, allowed = sample(1:100000, 40, replace=T), unique_services_per_patient = runif(40, 1, 5.2)
, duplicates_per_service = runif(40, 1.1, 16.2), services_per_patient = runif(40, 1.3, 70) )
# shiny plots on top_docs data
library(shiny)
ui <- fluidPage(
# Header title
titlePanel(title = h4("Top doctors plots - a histograms", align = "center")),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
# sliderInput( < ------------- HERE
selectInput("var", "1, Select the variables from top doc summary file",
choices =c( "service_total" = 1,
"ben_total" = 2,
"payment" = 3,
"charged" = 4,
"allowed" = 5,
"unique_services_per_patient" = 6,
"duplicates_per_service" = 7,
"services_per_patient" = 8), selected= 1 ),
br(),
sliderInput("bins", "2, Select the number of BINs for histogram", min = 5, max = 40, value=20),
br(),
radioButtons("color", "3, Select the color of histogram", choices =c("Green", "Red", "Yellow"), selected= "Green")
# ) < ------------- HERE
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("myhist")
)
))
server <- shinyServer(function(input, output) {
output$myhist <- renderPlot({
# generate var based on input$var from ui.R
col <- as.numeric(input$var)
hist(top_docs[,col], breaks = seq(0, max(top_docs[,col]), l = input$bins+1)
, col=input$color, main="Histogram of Top docs", xlab=names(top_docs[col]))
})
})
shinyApp(ui, server)