I've spent two days trying to create a Shiny app to no avail. It's fine just running the examples but when I want to modify it for my own preference, I just get constant errors and lack of functionality.
I have a simple dataset of 100 X observations and 100 Y observations. I want to plot histograms of both X and Y with slider inputs for bins. I also want to create a scatterplot of Y on X. I'd really appreciate some help here.
I'm not new to R but I'm new to Shiny. Is there a way I can use ggplot to create the visuals?
Many thanks.
This is a quick example with two different layouts. Use one of the ui.R of course. Put global.R in the same folder with ui.R and server.R
ui.R v1
library(shiny)
library(ggplot2)
shinyUI(fluidPage(
titlePanel("Quick Shiny Example"),
sidebarLayout(
sidebarPanel(
sliderInput("xBins",
"Number of bins for X variable:",
min = 1,
max = 50,
value = 30),
sliderInput("yBins",
"Number of bins for Y variable:",
min = 1,
max = 50,
value = 30)
),
mainPanel(
plotOutput("xDistPlot"),
plotOutput("yDistPlot"),
plotOutput("xyScatterPlot")
)
)
))
ui.R v2
library(shiny)
library(ggplot2)
shinyUI(fluidPage(
titlePanel("Quick Shiny Example"),
fluidRow(
column(width = 4,
sliderInput("xBins",
"Number of bins for X variable:",
min = 1,
max = 50,
value = 30)
),
column(width = 4,
sliderInput("yBins",
"Number of bins for Y variable:",
min = 1,
max = 50,
value = 30)
),
column(width = 4)
),
fluidRow(
column(width = 4,
plotOutput("xDistPlot")
),
column(width = 4,
plotOutput("yDistPlot")
),
column(width = 4,
plotOutput("xyScatterPlot")
)
)
))
server.R
library(shiny)
library(ggplot2)
shinyServer(function(input, output) {
output$xDistPlot <- renderPlot({
g <- ggplot(df, aes(x = x))
g <- g + geom_histogram(bins = input$xBins)
g
})
output$yDistPlot <- renderPlot({
g <- ggplot(df, aes(x = y))
g <- g + geom_histogram(bins = input$yBins)
g
})
output$xyScatterPlot <- renderPlot({
g <- ggplot(df, aes(x = x, y = y))
g <- g + geom_point()
g
})
})
global.R
df <- data.frame(
x = rnorm(100),
y = rnorm(100)*2
)
Here is my answer, with random numbers for X and Y, just as a quick idea. Adding ggplot to this should be easy.
library(shiny)
ui <- shinyUI(
fluidPage(
sliderInput("nrBinsX", "Number of bins to display for X", min = 2, max = 10, value = 5),
plotOutput("histX"),
sliderInput("nrBinsY", "Number of bins to display for Y", min = 2, max = 10, value = 5),
plotOutput("histY"),
plotOutput("scatterXY")
)
)
server <- shinyServer(function(input, output, session) {
dataFrame <- data.frame (
"X" = sample(100,100,replace = T),
"Y" = sample(100,100,replace = T)
)
getHist <- function (var,nr){
return (hist(
x = var,
breaks = seq(0,100,100/nr),
freq = T
) )
}
output$histX <- renderPlot({
return(
getHist( var = dataFrame$X,
nr = input$nrBinsX
) ) })
output$histY <- renderPlot({
return( return(
getHist( var = dataFrame$Y,
nr = input$nrBinsY
)
) ) })
output$scatterXY <- renderPlot({
return(
plot(x = dataFrame$X,
y = dataFrame$Y)
)
})
})
shinyApp(ui = ui, server = server)
Related
Please see attached image. Do you have suggestions how to avoid that the plot is outside the white area, or to make the grey area below the plot white?
ui <- dashboardPage(
# Application title
dashboardHeader(title=h4(HTML("Virus Coverage plot"))),
dashboardSidebar(
useShinyjs(),
selectInput("Taxa", "Taxa", choices = unique(files.Vir.DNA.df.test$V1))
),
dashboardBody(
tabsetPanel(
tabPanel("Taxa", plotOutput("myplot1"))
)
)
)
server <- function(input, output, session) {
data_selected <- reactive({
filter(files.Vir.DNA.df.test, V1 %in% input$Taxa)
})
output$myplot1 <- renderPlot({
#data_selected() %>%
# filter(Cancer=="Anus" | Cancer=="Cervix") %>%
p <- ggplot(data_selected(),aes(position,rowSums, fill = V1)) +
#theme_bw(base_size = 6) +
geom_bar(stat="identity") +
facet_grid(Cancer~. , scales = "free_x", space = "free_x", switch = "x") +
theme(strip.text.y = element_text(angle = 0),
strip.text.x = element_text(angle = 90),
strip.background = element_rect(colour = "transparent", fill = "transparent"),
plot.background = element_rect(colour = "white", fill = "white"),
panel.background = element_rect(colour = "white", fill = "white"),
axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
labs(y="Sum coverage within cancer type", x="", title="") +
scale_fill_manual(values=mycolors) +
theme(legend.position = "none")
#scale_y_log10()
print(p)
},res = 100,width = 600, height = 1200)
}
shinyApp(ui, server)
Your example isn't reproducible - so I made a new one.
You just need to wrap the plotOutput in a fluidRow:
library(shiny)
library(ggplot2)
library(datasets)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
# dashboardBody(plotOutput("myplot")) # exceeds body
dashboardBody(fluidRow(plotOutput("myplot"))) # works
)
server <- function(input, output, session) {
output$myplot <- renderPlot({
scatter <- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width))
scatter + geom_point(aes(color=Species, shape=Species)) +
xlab("Sepal Length") + ylab("Sepal Width") +
ggtitle("Sepal Length-Width")
}, height = 1200)
}
shinyApp(ui, server)
This is the output, that I would like to plot with shiny.
<constr <- c(+4,-3,-2,-5)
# Uhlig rejection
model1s <- uhlig.reject(Y=uhligdata, nlags=12, draws=200, subdraws=200, nkeep=100, KMIN=1,
KMAX=5, constrained = constr, constant=FALSE, steps=60)
irf1s <- model1s$IRFS
irfplot(irf1s)
# Uhlig penalty
model1d <- uhlig.penalty(Y=uhligdata, nlags=12, draws=200, subdraws=1000,nkeep=100, KMIN=1, KMAX=5, constrained=constr,
constant=FALSE, steps=60, penalty=100, crit=0.001)
irf1d <- model1d$IRFS
irfplot(irf1d)>
and below is my attemp. I am trying to have the test, lags and periods dynamic and based on them to have the IRFs plotted.
ui <- dashboardPage(
dashboardHeader(title = "НАЧАЛО"),
dashboardSidebar(
sidebarMenu(
menuItem("BVAR",
tabName = "test_tab",
icon = icon("dashboard"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "test_tab",
box(column(10,
radioButtons("test1",
label = "Изберете тест",
choices = c("Uhlig rejection", "Uhlig penalty")),
numericInput("nlags", "NLAGS", min = 1, max = 20, value = 1, step = 1),
numericInput("kmin", "KMIN", min = 1, max = 10, value = 1, step = 1),
numericInput("kmax", "KMAX", min = 2, max = 10, value = 2, step = 1),
submitButton("Submit"))),
box(column(12,
plotOutput("plot2",8))),)
)
))
server <- function(input, output){
modelselect <- reactive({
if(input$test1 == "Uhlig Rejection"){
fit <- uhlig.reject(uhligdata, nlags = input$nlags,constrained = constr, KMIN = input$kmin, KMAX = input$kmax)
return(fit)
}else
if(input$test1 == "Uhlig Penalty"){
fit <- uhlig.penalty(uhligdata,nlags = input$nlags, KMIN = input$kmin, KMAX = input$kmax)
return(fit)
}
})
myplot1 <- reactive({
if(input$test1 == "Uhlig Rejection"){
irfs <- modelselect()$IRFS
irfs} else
if(input$test1 == "Uglig Penalty"){
irfs <-modelselect()$IRFS
irfs}
})
output$plot2 <- renderPlot({
irfplot(myplot1())
})
}
shinyApp(ui = ui, server = server)
The dashboard loads fine but I cannot access the IRF plot. I wonder if the problem is with the reactive function or I do not access the model output correctly(I am quite a newbie to shiny)?
Is it possible to select/get only the input names of the widgets that have changed? Say that I have a Shiny App and that I deselect a box of a checkboxGroupInput. Is it possible to somehow get the inputId of that widget?
Here is a solution using basic shiny:
library(shiny)
ui <- fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
sliderInput("bins1",
"Number of bins 1:",
min = 1,
max = 50,
value = 30),
sliderInput("bins2",
"Number of bins 2:",
min = 1,
max = 50,
value = 30),
textOutput("printChangedInputs")
),
mainPanel(
plotOutput("distPlot1"),
plotOutput("distPlot2")
)
)
)
server <- function(input, output) {
output$distPlot1 <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins1 + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
output$distPlot2 <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins2 + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
previousInputStatus <- NULL
changedInputs <- reactive({
currentInputStatus <- unlist(reactiveValuesToList(input))
if(is.null(previousInputStatus)){
previousInputStatus <<- currentInputStatus
changedInputs <- NULL
} else {
changedInputs <- names(previousInputStatus)[previousInputStatus != currentInputStatus]
print(paste("Changed inputs:", changedInputs))
previousInputStatus <<- currentInputStatus
}
return(changedInputs)
})
output$printChangedInputs <- renderText({paste("Changed inputs:", changedInputs())})
}
shinyApp(ui = ui, server = server)
Edit: Another way would be to listen for the JavaScript event shiny:inputchanged:
library(shiny)
ui <- fluidPage(
tags$head(
tags$script(
"$(document).on('shiny:inputchanged', function(event) {
if (event.name != 'changed') {
Shiny.setInputValue('changed', event.name);
}
});"
)
),
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
sliderInput("bins1",
"Number of bins 1:",
min = 1,
max = 50,
value = 30),
sliderInput("bins2",
"Number of bins 2:",
min = 1,
max = 50,
value = 30),
textOutput("changedInputs")
),
mainPanel(
plotOutput("distPlot1"),
plotOutput("distPlot2")
)
)
)
server <- function(input, output) {
output$distPlot1 <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins1 + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
output$distPlot2 <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins2 + 1)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
output$changedInputs <- renderText({paste("Changed inputs:", input$changed)})
}
shinyApp(ui = ui, server = server)
Please see this for more information.
I have created a small Shiny Application using Plotly heatmap and intend to use withSpinner to plot Heat Map depending on user input. Currently i have two issues.
a.) WithSpinner appears only for the first time when heat map is generated. It doesn't appear if the User input is changed and replotting is done.
b.) On change of User input, the previous heatmap is shown instead of spinner and it refreshes after sometime. I intend to use spinner instead of showing old plot during redrawing of heatmap.
library(shiny)
library(shinydashboard)
library(shinycssloaders)
library(shinyjs)
library(plotly)
ui <- shinydashboard::dashboardPage(
# Dashboard header
shinydashboard::dashboardHeader(),
# Dashboard sidebar
shinydashboard::dashboardSidebar(disable = TRUE),
# Dashboard body
shinydashboard::dashboardBody(
id = "myBody",
# Tab items
shinydashboard::tabItem(tabName = "visual",
fluidRow(
shinydashboard::tabBox(id="tabBix1",
shiny::tabPanel(
"Parameters & Settings",
value = "paramsetting",
sliderInput("obs", "Number of observations:",
min = 0, max = 1000, value = 500
)),
shiny::tabPanel(
"PlotOutput",
value = "Ops",
withSpinner(plotly::plotlyOutput("plotNewExp"))
)
)
))
)
)
server <- function(input, output, session) {
p <- NULL
observeEvent(input$obs,{
p <- NULL
m <- matrix(rnorm(input$obs), nrow = 3, ncol = 3)
output$plotNewExp <- plotly::renderPlotly({
p <- plot_ly(
x = c("a", "b", "c"), y = c("d", "e", "f"),
z = m, type = "heatmap"
)
})
})
}
shinyApp(ui=ui,server=server)
If you try this you will see that the spinner is working but it is fast. So you probably don't have the time to see it when you switch from one tab to the other.
ui <- shinydashboard::dashboardPage(
# Dashboard header
shinydashboard::dashboardHeader(),
# Dashboard sidebar
shinydashboard::dashboardSidebar(disable = TRUE),
# Dashboard body
shinydashboard::dashboardBody(
id = "myBody",
# Tab items
shinydashboard::tabItem(tabName = "visual",
fluidRow(
shinydashboard::tabBox(
tabPanel(
"Parameters & Settings",
value = "paramsetting",
sliderInput("obs", "Number of observations:",
min = 0, max = 1000, value = 500
),
withSpinner(plotly::plotlyOutput("plotNewExp")))
# tabPanel(
# "PlotOutput",
# withSpinner(plotly::plotlyOutput("plotNewExp"))
# )
)
))
)
)
server <- function(input, output, session) {
# p <- NULL
# observeEvent(input$obs,{
# p <- NULL
m <- reactive({matrix(rnorm(input$obs), nrow = 3, ncol = 3)})
output$plotNewExp <- renderPlotly({
p <- plot_ly(
x = c("a", "b", "c"), y = c("d", "e", "f"),
z = m(), type = "heatmap"
)
# })
})
}
shinyApp(ui=ui,server=server)
or if you add a delay, you will see it is working.
library(shinyjs)
ui <- shinydashboard::dashboardPage(
# Dashboard header
shinydashboard::dashboardHeader(),
# Dashboard sidebar
shinydashboard::dashboardSidebar(disable = TRUE),
# Dashboard body
shinydashboard::dashboardBody(
useShinyjs(),
id = "myBody",
# Tab items
shinydashboard::tabItem(tabName = "visual",
fluidRow(
shinydashboard::tabBox(id="tabBix1",
shiny::tabPanel(
"Parameters & Settings",
value = "paramsetting",
sliderInput("obs", "Number of observations:",
min = 0, max = 1000, value = 500
)),
shiny::tabPanel(
"PlotOutput",
value = "Ops",
withSpinner(plotly::plotlyOutput("plotNewExp"))
)
)
))
)
)
server <- function(input, output, session) {
# p <- NULL
Graph <- function() {
p <- NULL
m <- matrix(rnorm(input$obs), nrow = 3, ncol = 3)
output$plotNewExp <- plotly::renderPlotly({
p <- plot_ly(
x = c("a", "b", "c"), y = c("d", "e", "f"),
z = m, type = "heatmap"
)
})
}
observeEvent(input$obs,{
delay(4000, Graph())
})
}
shinyApp(ui=ui,server=server)
I have an application which works fine locally and I would like to deploy it to shinyapps.io. I created a directory (dataviz) and the application code is in a file called app.R. When running deployApp("dataviz") from RStudio, it starts deploying but reaches a point where it fails with the error:
** preparing package for lazy loading
Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) :
there is no package called ‘htmltools’
ERROR: lazy loading failed for package ‘rcdimple’
* removing ‘/usr/local/lib/R/site-library/rcdimple’
################################### End Log ###################################
Error: Unhandled Exception: Child Task 27328802 failed: Error building image: Error building rcdimple (0.1). Build exited with non-zero status: 1
Not sure what could be happening here, any help greatly appreciated.
The app.R is as so
## app.R ##
library(shinydashboard)
library(shiny)
require(htmltools)
require(htmlwidgets)
library(rcdimple) #devtools::install_github("timelyportfolio/rcdimple")
library(curl) #devtools::install_github("jeroenooms/curl")
library(plyr) # for round_any
library(rCharts)
library(ggvis)
library(reshape2)
indicators <- read.csv(curl("https://raw.githubusercontent.com/kilimba/msc-impl-R/master/dataviz/data/testindicators.csv"))
choices <- as.vector(indicators$label)
indicators$label <- as.character(indicators$label)
indicators$file <- paste("",indicators$file,"",sep="")
getHeatMapData <- function(data,indicator){
df <- data
if(indicator$rate == "Y"){
hmap_df <- aggregate(cbind(denominator,numerator) ~ year + agegrp,df,sum)
hmap_df$rate <- round((hmap_df$numerator/hmap_df$denominator)*indicator$multiplier,2)
names(hmap_df)
}else{
hmap_df <- aggregate(denominator ~ agegrp + year,df, sum)
}
hmap_df$year <- factor(hmap_df$year)
# Helps to order the y-axis labels otherwise labels appear in mixed order
hmap_df$agegrp <- factor(hmap_df$agegrp, levels = rev(as.vector(unique(hmap_df$agegrp))))
return(hmap_df)
}
getData <- function(startyr,endyear,outcome_data) {
data <- subset(outcome_data,(year >= startyr & year <= endyear))
return(data)
}
getDataByAgeGroup <-function(data,agegrp){
d <- data
a <- agegrp
selection <- subset(d,agegrp==a)
return(selection)
}
lineChart <- function(data,agegrp,indicator){
if(indicator$rate == "Y"){
selection <- data
selection$rate <- round((selection$numerator/selection$denominator)*indicator$multiplier,2)
selection$sex <- ifelse(selection$sex == 1, "MALE", "FEMALE")
max_y <- round_any(max(selection$rate), 10, f = ceiling)
min_y <- round_any(min(selection$rate), 10, f = floor)
selection <- getDataByAgeGroup(selection,agegrp)
plot <- nPlot(rate ~ year,
data = selection,
type = "lineChart",
group = "sex",
height = 250,
width = 450 )
# Explicitly set year tick values for every year
plot$xAxis(tickValues = do.call(seq, c(as.list(range(selection$year)), 1)),rotateLabels= -40,showMaxMin = "true")
plot$chart(useInteractiveGuideline = "true", transitionDuration = 500)
plot$chart(forceY = c(min_y, max_y))
plot$chart(color = c("steelblue","firebrick"))
# Add axis labels and format the tooltip
plot$yAxis(axisLabel = paste("Rate per",indicator$multiplier), width = 62)
plot$xAxis(axisLabel = "Year")
return(plot)
}else{
selection <- data
selection$sex <- ifelse(selection$sex == 1, "MALE", "FEMALE")
max_y <- round_any(max(selection$denominator), 10, f = ceiling)
min_y <- round_any(min(selection$denominator), 10, f = floor)
selection <- getDataByAgeGroup(selection,agegrp)
plot <- nPlot(denominator ~ year,
data = selection,
type = "lineChart",
group = "sex",
height = 250,
width = 450 )
# Explicitly set year tick values for every year
plot$xAxis(tickValues = do.call(seq, c(as.list(range(selection$year)), 1)),rotateLabels= -40,showMaxMin = "true")
plot$chart(useInteractiveGuideline = "true", transitionDuration = 500)
plot$chart(forceY = c(min_y, max_y))
plot$chart(color = c("steelblue","firebrick"))
# Add axis labels and format the tooltip
plot$yAxis(axisLabel = "Population", width = 62)
plot$xAxis(axisLabel = "Year")
return(plot)
}
}
# Heat Map
heatmap <- function(data,indicator){
dat <- getHeatMapData(data,indicator)
if(indicator$rate == "Y"){
dat <- rename(dat, c("agegrp" = "Age","year" = "Year", "rate" = "Rate"))
dat %>%
ggvis(~Year, ~Age, fill = ~Rate) %>%
layer_rects(width = band(), height = band()) %>%
add_relative_scales() %>%
set_options(height = 200, width = 410, keep_aspect = TRUE) %>%
add_axis("y", title="")%>%
scale_nominal("x", padding = 0, points = FALSE) %>%
scale_nominal("y", padding = 0, points = FALSE) %>%
scale_numeric("fill",range = c("lightsteelblue","red")) %>%
hide_legend("fill") %>%
add_tooltip(function(d) {
if(is.null(d)) return(NULL)
paste0(names(d), ": ", format(d), collapse = "<br />")
}
) %>%
bind_shiny("heatmap")
}else{
dat <- rename(dat, c("agegrp" = "Age","year" = "Year", "denominator" = "Count"))
dat %>%
ggvis(~Year, ~Age, fill = ~Count) %>%
layer_rects(width = band(), height = band()) %>%
add_relative_scales() %>%
set_options(height = 200, width = 410, keep_aspect = TRUE) %>%
add_axis("y", title="")%>%
scale_nominal("x", padding = 0, points = FALSE) %>%
scale_nominal("y", padding = 0, points = FALSE) %>%
scale_numeric("fill",range = c("lightsteelblue","red")) %>%
hide_legend("fill") %>%
add_tooltip(function(d) {
if(is.null(d)) return(NULL)
paste0(names(d), ": ", format(d), collapse = "<br />")
}
) %>%
bind_shiny("heatmap")
}
}
# DimpleJS pyramid
dPyramid <- function(startyear, endyear, data, colors=c("steelblue","firebrick"),indicator) {
dat <- getData(startyear,endyear,data)
if(indicator$rate == "Y"){
dat$denominator <- ifelse(dat$sex == 1, -1 * dat$denominator, 1 * dat$denominator)
dat$Gender <- ifelse(dat$sex == 1,"Male", "Female")
dat$Rate <- (dat$numerator/dat$denominator)*indicator$multiplier
max_x <- round_any(max(dat$Rate), 10, f = ceiling)
min_x <- round_any(min(dat$Rate), 10, f = floor)
dat <- rename(dat, c("agegrp" = "Age"))
d1 <- dimple(
x = "Rate",
y = "Age",
groups = "Gender",
data = dat,
type = 'bar')
d1 <- yAxis(d1, type = "addCategoryAxis", orderRule = "Age")
d1 <- xAxis(d1,type = "addMeasureAxis")
# Ensure fixed x-axis independent of year selected
d1 <- xAxis(d1, overrideMax = max_x, overrideMin = min_x)
if (!is.null(colors)){
d1 <- colorAxis(
d1,
type = "addColorAxis",
colorSeries = "sex",
palette = colors
)
}
# For storyboarding
if (endyear - startyear >= 1) {
d1 <- tack(d1, options = list( storyboard = "year" ) )
}
return(d1)
}
else{
dat$denominator <- ifelse(dat$sex == 1, -1 * dat$denominator, 1 * dat$denominator)
dat$Gender <- ifelse(dat$sex == 1,"Male", "Female")
max_x <- round_any(max(dat$denominator), 10, f = ceiling)
min_x <- round_any(min(-1*dat$denominator), 10, f = floor)
dat <- rename(dat,c("denominator" = "Count","agegrp" = "Age"))
d1 <- dimple(
x = "Count",
y = "Age",
groups = "Gender",
data = dat,
type = 'bar')
d1 <- yAxis(d1, type = "addCategoryAxis", orderRule = "Age")
d1 <- xAxis(d1,type = "addMeasureAxis")
# Ensure fixed x-axis independent of year selected
d1 <- xAxis(d1, overrideMax = max_x, overrideMin = min_x)
if (!is.null(colors)){
d1 <- colorAxis(
d1,
type = "addColorAxis",
colorSeries = "sex",
palette = colors
)
}
# For storyboarding
if (endyear - startyear >= 1) {
d1 <- tack(d1, options = list( storyboard = "year" ) )
}
return(d1)
}
}
suppressMessages(
singleton(
addResourcePath(
get_lib("nvd3")$name
,get_lib("nvd3")$url
)
)
)
ui <- dashboardPage(
dashboardHeader(title = "HealthData Viz"),
dashboardSidebar(
sidebarMenu(
menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
menuItem("Presentations", tabName = "widgets", icon = icon("file-powerpoint-o"))
),
tags$br(),
tags$fieldset(checkboxInput("doAnimate", "Animate Pyramid",value = TRUE),
tags$p("(Uncheck to select specific year)")),
conditionalPanel(
condition = "input.doAnimate == false",
uiOutput("choose_year")
),
uiOutput("choose_agegrp")
,
uiOutput("choose_dataset")
),
dashboardBody(
tags$head(get_assets_shiny(get_lib("nvd3"))[-3]),
tabItems(
# First tab content
tabItem(tabName = "dashboard",
fluidRow(
box(dimpleOutput("distPlot", height = 250)),
box(showOutput("distPlot2","nvd3",add_lib=F))
),
fluidRow(
#box(infoBoxOutput("informationBox")),
infoBox("About", textOutput("caption"), icon = icon("info-circle"),width = 6),
(
#uiOutput("ggvis_ui"),
box(ggvisOutput("heatmap"))
)
)
),
# Second tab content
tabItem(tabName = "widgets",
h2("Links to interactive scientific presentations will go here...")
)
)
)
)
server <- function(input, output) {
output$choose_dataset <- renderUI({
selectInput("outcome", "Select Outcome", choices, selected="Population Structure",width="95%")
})
output$choose_agegrp <- renderUI({
selectInput("agegrp", "Select Age Group",
choices = c("00-04","05-09","10-14","15-19","20-24","25-29",
"30-34","35-39","40-44","45-49","50-54",
"55-59","60-64","65-69","70-74","75-79",
"80-84","85+"), selected="00-04",width="95%")
})
#############################################################
# PYRAMID
#############################################################
observe({
if(!is.null(input$outcome)){
selected_outcome <- input$outcome
selected_indicator <- subset(indicators,indicators$label == selected_outcome)
outcome_data <- reactive({
read.csv(curl(as.character(selected_indicator$file)))
})
d <- reactive({outcome_data()})
minYear <- reactive({min(d()$year)})
maxYear <- reactive({max(d()$year)})
observe({
if(input$doAnimate){
output$distPlot <- renderDimple({
dPyramid(minYear(), maxYear(),data = outcome_data(), indicator = selected_indicator)
})
}else{
years <- as.vector(unique(outcome_data()$year))
output$choose_year <- renderUI({
selectInput("startyr", "Select Pyramid Year", years, width="95%")
})
output$distPlot <- renderDimple({
if(!is.null(input$startyr)){
startyear <- as.numeric(input$startyr)
# Start year and end year are equal we only want cross-sectional pyramid
# for a single selected year
dPyramid(startyear, startyear, data = outcome_data(),indicator = selected_indicator)
}
})
}
})
}
})
###############################################
observe({
if(!is.null(input$outcome)
& !is.null(input$agegrp)){
selected_outcome <- input$outcome
selected_indicator <- subset(indicators,indicators$label == selected_outcome)
outcome_data <- reactive({
read.csv(curl(as.character(selected_indicator$file)))
})
d <- reactive({outcome_data()})
output$caption <- renderText({
return(paste("You are currently viewing",
ifelse(selected_indicator$rate=="N",paste(input$outcome,".\n",selected_indicator$description),
paste(input$outcome,"(per",selected_indicator$multiplier,"population).\n",selected_indicator$description))))
})
################################################
# Line chart
################################################
output$distPlot2 <- renderChart2({
lineChart(outcome_data(),input$agegrp,selected_indicator)
})
#################################################
# HEATMAP
#################################################
heatmap(outcome_data(),selected_indicator)
}
})
}
shinyApp(ui, server)
Tumaini
#timelyportfolio - It seems dependencies to htmltools was not listed in the DESCRIPTION file of the rcdimple package. Forked the package from https://github.com/timelyportfolio/rcdimple and added the dependencies to the DESCRIPTION file (https://github.com/kilimba/rcdimple). Can now deploy a shiny app which uses the rcdimple package to shinayapps.io. Have made a Pull Request to master branch