Boxplots in R Shiny App showing only flat lines - r

I have looked at similar posts and the responses don't seem to answer my question. I am trying to develop an R Shiny App (This is my first Shiny App) to draw a boxplot for some data. I am adapting it from some code that produces accurate boxplots in the console. The plots should look similar to this (I did simplify the labels for the app):
correct plot
When I run the app, I see the following:
app plot
Here is some reproducible code. Any insights would be greatly appreciated:
library(dplyr)
library(ggplot2)
library(shiny)
AlkCalcs2 <- data.frame(matrix(ncol = 6, nrow = 250))
AlkCalcs2$climate <- sample.int(2, 250, replace = TRUE)
AlkCalcs2$block <- sample.int(3, 250, replace = TRUE)
AlkCalcs2$treatment <- factor(sample.int(4, 250, replace = TRUE),
labels = c("Control", "Compost", "Basalt", "Basalt and Compost"))
AlkCalcs2$pre_dilution_alk_endp <- rnorm(250, 91, 58)
AlkCalcs2$pre_dilution_alk_infl <- rnorm(250, 65, 59)
AlkCalcs2$pre_dilution_alk_gran <- rnorm(250, 72, 55)
# Define server logic
server <- function(input, output, session) {
output$boxplot <- renderPlot({
ggplot(data = filter(AlkCalcs2,
climate == input$climate,
block %in% input$block)) +
geom_boxplot(mapping = aes(x = treatment, y = input$method)) +
labs(y = "Alkalinity",
x = element_blank(),
title = paste("Climate ", input$climate, sep = ""),
subtitle = paste("Block(s) ", input$block, sep = "")) +
theme(plot.title = element_text(size = 16, hjust = 0.5),
plot.subtitle = element_text(size = 16, hjust = 0.5),
axis.text = element_text(size = 12),
axis.title = element_text(size = 14))
})
}
# Define UI for application that draws a boxplot
ui <- fluidPage(
# Application title
titlePanel("Soybean Titration Analysis"),
# Sidebar with inputs
sidebarLayout(
sidebarPanel(
radioButtons(inputId = "method",
label = "Alkalinity Calculation Method:",
choiceNames = c('Endpoint', 'Inflection Point', 'Gran Plotting'),
choiceValues = c('pre_dilution_alk_endp',
'pre_dilution_alk_infl',
'pre_dilution_alk_gran')),
radioButtons(inputId = "climate",
label = "Select Climate:",
choices = c(1, 2)),
checkboxGroupInput(inputId = "block",
label = "Select Block (Choose at least one):",
choices = c(1, 2, 3),
selected = 1)
),
# Show a boxplot of the data
mainPanel("Boxplot", plotOutput('boxplot'))
)
)
# Run the application
shinyApp(ui = ui, server = server)

It's more a ggplot issue than Shiny issue. Your plot data isn't right.
library(dplyr)
library(ggplot2)
library(shiny)
AlkCalcs2 <- data.frame(matrix(ncol = 6, nrow = 250))
AlkCalcs2$climate <- sample.int(2, 250, replace = TRUE)
AlkCalcs2$block <- sample.int(3, 250, replace = TRUE)
AlkCalcs2$treatment <- factor(sample.int(4, 250, replace = TRUE),
labels = c("Control", "Compost", "Basalt", "Basalt and Compost"))
AlkCalcs2$pre_dilution_alk_endp <- rnorm(250, 91, 58)
AlkCalcs2$pre_dilution_alk_infl <- rnorm(250, 65, 59)
AlkCalcs2$pre_dilution_alk_gran <- rnorm(250, 72, 55)
AlkCalcs2[['pre_dilution_alk_endp']]
# Define server logic
server <- function(input, output, session) {
output$boxplot <- renderPlot({
plot_data <- filter(AlkCalcs2,
climate == input$climate,
block %in% input$block)
ggplot(data = plot_data) +
geom_boxplot(mapping = aes(x = treatment, y = .data[[input$method]])) +
labs(y = "Alkalinity",
x = element_blank(),
title = paste("Climate ", input$climate, sep = ""),
subtitle = paste("Block(s) ", input$block, sep = "")) +
theme(plot.title = element_text(size = 16, hjust = 0.5),
plot.subtitle = element_text(size = 16, hjust = 0.5),
axis.text = element_text(size = 12),
axis.title = element_text(size = 14))
})
}
# Define UI for application that draws a boxplot
ui <- fluidPage(
# Application title
titlePanel("Soybean Titration Analysis"),
# Sidebar with inputs
sidebarLayout(
sidebarPanel(
radioButtons(inputId = "method",
label = "Alkalinity Calculation Method:",
choiceNames = c('Endpoint', 'Inflection Point', 'Gran Plotting'),
choiceValues = c('pre_dilution_alk_endp',
'pre_dilution_alk_infl',
'pre_dilution_alk_gran')),
radioButtons(inputId = "climate",
label = "Select Climate:",
choices = c(1, 2)),
checkboxGroupInput(inputId = "block",
label = "Select Block (Choose at least one):",
choices = c(1, 2, 3),
selected = 1)
),
# Show a boxplot of the data
mainPanel("Boxplot", plotOutput('boxplot'))
)
)
# Run the application
shinyApp(ui = ui, server = server)

Related

How to customise choropleth map tooltips in R shiny app

I have tried to customise my choropleth map tooltips in R shiny app, which doesn't work. I tried both paste0 and paste, and it does not work either.
Here is my code:
ui <- fixedPage(
titlePanel("Map"),
fixedRow(
column(5
),
),
column(
12,
plotlyOutput('map',
width = 1000,
height = 1000)
)
)
server <- function(input, output) {
output$map = renderPlotly({
map<- country_choropleth(AADS_map,
num_colors=8,
text = paste0("value:", value)
)+
scale_fill_brewer(palette="RdPu") +
theme(plot.title = element_text (h = 0.5, size = 18),
legend.title = element_text(size = 10),
legend.text = element_text(size = 12)
) +
labs(fill = "Number of Accident",
title = "The distribution of accidents in countries from 1981 to 2019")
map <- ggplotly(map,
tooltip = c("text"))
})}

Shiny button doesn't work when I click it. Can sb help me?

I want to add 3 different buttons to show different plot but use the same input information.
But now I was trapped in the first step.
when I click the first button which is linked to the first plot but it didn't work.
Can somebody help me to deal with it. Thanks a lot.
Here is my sample code below:
library(shiny)
library(ggplot2)
library(ggpubr)
library(dplyr)
library(tidyr)
#####
mean_data <- data.frame(
Name = c(paste0("Group_", LETTERS[1:20])),
matx <- matrix(sample(1:1000, 1000, replace = T), nrow = 20)
)
names(mean_data)[-1] <- c(paste0("Gene_", 1:50))
sd_data <- data.frame(
Name = c(paste0("Group_", LETTERS[1:20])),
matx <- matrix(runif(1000, 5, 10), nrow = 20)
)
names(sd_data)[-1] <- c(paste0("Gene_", 1:50))
# Prepare dataset.
# 1. Bind mean and sd data
# 2. Reshape
data <- bind_rows(list(
mean = mean_data,
sd = sd_data
), .id = "stat")
data_mean_sd <- data %>%
pivot_longer(-c(Name, stat), names_to = "Gene", values_to = "value") %>%
pivot_wider(names_from = "stat", values_from = "value")
###
ui <- fluidPage(
fluidRow(
column(8,offset = 3,
h2("Gene_FPKM Value Barplot")
)
),
fluidRow(
column(8,offset = 3,
selectInput(
"selectGeneSymbol",
"Select Gene Symbol:",
choices = unique(data_mean_sd$Gene),
multiple =F,
width = 800,
selected = "Igfbp7"
))
),
fluidRow(
column(8,offset = 3,
actionButton(inputId = "FPKM", label = "FPKM"),
actionButton(inputId = "logFC", label = "logFC"),
actionButton(inputId = "logFC&FPKM",label = "logFC&FPKM")
)
),
fluidRow(
column(3)
),
fluidRow(
column(3)
),
fluidRow(
column(12,align="center",
plotOutput(outputId = "barplot1",height = 700, width = 1300)
)
),
fluidRow(
column(12,align="center",
plotOutput(outputId = "barplot2",height = 700, width = 1300)
)
)
)
server <- function(input, output) {
data_FPKM <- eventReactive(input$FPKM, {
plot_data <- reactive({
subset(data_mean_sd, Gene %in% input$selectGeneSymbol)
})
ggplot(data = plot_data(), aes(x = Name, y = mean,fill=Name)) +
geom_bar(stat = "identity", position = position_dodge(0.9), width = 0.9) +
geom_errorbar(aes(ymin = mean - sd, ymax = mean + sd), width = .2, position = position_dodge(0.9)) +
theme_classic2() +
rotate_x_text(angle = 45) +
theme(legend.position = "none") +
labs(title = input$GeneSymbol, x = NULL, y = "FPKM_value") +
theme(plot.title = element_text(hjust = 0.5)) +
theme(plot.margin = unit(c(20, 5, 1, 5), "mm"))+
theme(axis.text.x=element_text(vjust=1,size=12))
}) ## 建立 按钮与 数据的关系
output$barplot <- renderPlot(
{
barplot(data_FPKM())
})
}
# Create Shiny app ----
shinyApp(ui = ui, server = server)
Who can help me to find where the wrong with my code. Many thanks
Here is a way to get output for the 1st plot on click of 1st button. You can use the same process for other plots.
library(shiny)
library(ggplot2)
mean_data <- data.frame(
Name = c(paste0("Group_", LETTERS[1:20])),
matx <- matrix(sample(1:1000, 1000, replace = T), nrow = 20)
)
names(mean_data)[-1] <- c(paste0("Gene_", 1:50))
sd_data <- data.frame(
Name = c(paste0("Group_", LETTERS[1:20])),
matx <- matrix(runif(1000, 5, 10), nrow = 20)
)
names(sd_data)[-1] <- c(paste0("Gene_", 1:50))
# Prepare dataset.
# 1. Bind mean and sd data
# 2. Reshape
data <- bind_rows(list(
mean = mean_data,
sd = sd_data
), .id = "stat")
data_mean_sd <- data %>%
pivot_longer(-c(Name, stat), names_to = "Gene", values_to = "value") %>%
pivot_wider(names_from = "stat", values_from = "value")
###
ui <- fluidPage(
fluidRow(
column(8,offset = 3,
h2("Gene_FPKM Value Barplot")
)
),
fluidRow(
column(8,offset = 3,
selectInput(
"selectGeneSymbol",
"Select Gene Symbol:",
choices = unique(data_mean_sd$Gene),
multiple =F,
width = 800,
selected = "Igfbp7"
))
),
fluidRow(
column(8,offset = 3,
actionButton(inputId = "FPKM", label = "FPKM"),
actionButton(inputId = "logFC", label = "logFC"),
actionButton(inputId = "logFC&FPKM",label = "logFC&FPKM")
)
),
fluidRow(
column(3)
),
fluidRow(
column(3)
),
fluidRow(
column(12,align="center",
plotOutput(outputId = "barplot1",height = 700, width = 1300)
)
),
fluidRow(
column(12,align="center",
plotOutput(outputId = "barplot2",height = 700, width = 1300)
)
)
)
server <- function(input, output) {
plot_data <- reactive({
subset(data_mean_sd, Gene %in% input$selectGeneSymbol)
})
v <- reactiveValues(barplot1 = NULL,barplot2 = NULL)
observeEvent(input$FPKM, {
ggplot(data = plot_data(), aes(x = Name, y = mean,fill=Name)) +
geom_bar(stat = "identity", position = position_dodge(0.9), width = 0.9) +
geom_errorbar(aes(ymin = mean - sd, ymax = mean + sd), width = .2, position = position_dodge(0.9)) +
theme_classic2() +
rotate_x_text(angle = 45) +
theme(legend.position = "none") +
labs(title = input$GeneSymbol, x = NULL, y = "FPKM_value") +
theme(plot.title = element_text(hjust = 0.5)) +
theme(plot.margin = unit(c(20, 5, 1, 5), "mm"))+
theme(axis.text.x=element_text(vjust=1,size=12)) -> v$barplot1
})
output$barplot1 <- renderPlot({
v$barplot1
})
}
# Create Shiny app ----
shinyApp(ui = ui, server = server)

Cannot disconnect connections in shiny app using pool package

I have my shiny app in AWS ubuntu server attached with mysql database, my app doesnot work sometimes when number of database connection exceeded(16 new connections). I tried several ways from various sources in internet but not able to get the required solution.
Furthure i am also getting warning you have leaked pool object . I am attaching the sample code.
library("shiny")
library("shinydashboard")
library("pool")
library(ggplot2)
library("DBI")
library(plotly)
pool <- dbPool(drv = RMySQL::MySQL(),dbname = "db",host = "database.cw5east-2.rds.amazonaws.com",username = "host",password = "host", port = 3306)
mychoices = dbGetQuery(pool,"select available_scenario from scenario_name;")
ui <- (fluidPage(
titlePanel("Demonstration of renderUI in shiny - Dymanically creating the tabs based on user inputs"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = 'n', "available scenarios", choices = mychoices, multiple = TRUE),
verbatimTextOutput("selected")
),
mainPanel(
plotOutput('Cost'),
uiOutput('tabs')
)
)
))
server <- (function(input,output,session){
output$tabs = renderUI({
par(mfrow = c(2, 2))
if(!is.null(input$n)){
x <- input$n
y <- length(x)
z <- dbGetQuery(pool,paste0("select scenario_key from scenario_name where available_scenario = '",x[y],"'"))
frame <- dbGetQuery(pool,paste0("select x,price from plot1 where scenario_key ='",z,"'"))
frame1 <- dbGetQuery(pool,paste0("select obj,runs from plot2 where scenario_key ='",z,"'"))
frame2 <- dbGetQuery(pool,paste0("select V1,V2,V3 from tableee where scenario_key ='",z,"'"))
runs <- dbGetQuery(pool,paste0(" select count(*) from plot2 where scenario_key ='",z,"'"))
b<-dbGetQuery(pool, paste0("select scenario_key from scenario_name where available_scenario = '",input$n,"'"))
Tabs <- lapply(paste("Scenario name:", input$n, sep=" "), tabPanel,
renderPlotly({
ggplot(frame, aes(x=x,y=price,fill=price)) + # basic graphical object
geom_col(width = 0.3)+
#geom_bar(position = 'dodge',stat = "identity")+ # first layer
xlab(NULL)+ylab("Price in USD")+
geom_text(aes(label=price),size=5,position=position_dodge(width=0.9), vjust=-0.25)+
theme_minimal()+
theme(axis.text = element_text(size = 12),
axis.title = element_text(size=16),
axis.text.y =element_text(angle = 90,hjust = 1))
}),
renderPlotly({
ggplot(frame1,aes(x=runs,y=obj))+
geom_col(width=0.3,fill='orangered')+
geom_hline(aes(yintercept=mean(obj,na.rm = T),color="Mean"),linetype='dashed',size=1)+
scale_color_manual(values = "blue")+
labs(x= 'Day Number',y='Reveneue in USD',color=NULL)+
theme_minimal()+theme(axis.text = element_text(size = 12),
axis.title = element_text(size=16),
axis.text.y= element_text(angle = 90,hjust = 1) )
}),
DT::renderDataTable({
frame2
},colnames=c('Day','Total Wt(kg)','Total Pcs','Revenue($)')
)
)
do.call(tabsetPanel, Tabs)}
})
})
shinyApp(ui, server)

How to remove text (data labels) from a plot in a shiny app?

Hello I have created a shiny app which creates a scatter plot between selected variables. Then when I click on a data point the name of the point is printed in the plot. The problem is that when I update the plot with other variables the printed are not erased. Generally I would like some ideas on how remove the data labels from my plot.
library(shiny)
library(ggplot2)
library(plotly)
library(dplyr)
library(htmlwidgets)
js <- HTML(
"Shiny.addCustomMessageHandler('resetValue', function(variableName){
Shiny.onInputChange(variableName, null);
}
);"
)
fluidPage(
tags$head(tags$script(js)),
# App title ----
titlePanel(div("CROSS CORRELATION",style = "color:blue")),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(width = 3
),
# Main panel for displaying outputs ----
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Table",
shiny::dataTableOutput("contents")),
tabPanel("Correlation Plot",
tags$style(type="text/css", "
#loadmessage {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
padding: 5px 0px 5px 0px;
text-align: center;
font-weight: bold;
font-size: 100%;
color: #000000;
background-color: #CCFF66;
z-index: 105;
}
"),conditionalPanel(condition="$('html').hasClass('shiny-busy')",
tags$div("Loading...",id="loadmessage")
),
fluidRow(
column(3, uiOutput("lx1")),
column(3,uiOutput("lx2"))),
hr(),
fluidRow(
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"
),
column(3,uiOutput("td")),
column(3,uiOutput("an"))
),
fluidRow(
plotlyOutput("sc"))
)
)
)))
#server.r
function(input, output,session) {
output$lx1<-renderUI({
selectInput("lx1", label = h4("Select 1st Expression Profile"),
choices = colnames(mtcars)
)
})
output$lx2<-renderUI({
selectInput("lx2", label = h4("Select 2nd Expression Profile"),
choices = colnames(mtcars)
)
})
output$td<-renderUI({
radioButtons("td", label = h4("Trendline"),
choices = list("Add Trendline" = "lm", "Remove Trendline" = ""),
selected = "")
})
output$an<-renderUI({
radioButtons("an", label = h4("Correlation Coefficient"),
choices = list("Add Cor.Coef" = cor(subset(mtcars, select=c(input$lx1)),subset(mtcars, select=c(input$lx2))), "Remove Cor.Coef" = ""),
selected = "")
})
# 1. create reactive values
vals <- reactiveValues()
# 2. create df to store clicks
vals$click_all <- data.frame(x = numeric(),
y = numeric(),
label = character())
# 3. add points upon plot click
observeEvent({event_data("plotly_click", source = "select")}, {
# get clicked point
click_data <- event_data("plotly_click", source = "select")
# check if from correct curve
if(!is.null(click_data) && click_data[["curveNumber"]] == 2) {
# get data for current point
label_data <- data.frame(x = click_data[["x"]],
y = click_data[["y"]],
label = click_data[["key"]],
stringsAsFactors = FALSE)
# add current point to df of all clicks
vals$click_all <- merge(vals$click_all,
label_data,
all = TRUE)
}
})
output$sc<-renderPlotly({
mtcars$model <- row.names(mtcars)
if(input$td=="lm"){
p1 <- ggplot(mtcars, aes_string(x = input$lx1, y = input$lx2,key = "model",group = 1))+
# Change the point options in geom_point
geom_point(color = "darkblue") +
# Change the title of the plot (can change axis titles
# in this option as well and add subtitle)
labs(title = "Cross Correlation") +
# Change where the tick marks are
scale_x_continuous(breaks = seq(0, 35, 5)) +
scale_y_continuous(breaks = seq(0, 35, 5)) +
# Change how the text looks for each element
theme(title = element_text(family = "Calibri",
size = 10,
face = "bold"),
axis.title = element_text(family = "Calibri Light",
size = 16,
face = "bold",
color = "darkgrey"),
axis.text = element_text(family = "Calibri",
size = 11))+
theme_bw()+
annotate("text", x = 5, y = 5, label = as.character(input$an))+
geom_smooth(aes(group = 1))+
# 4. add labels for clicked points
geom_text(data = vals$click_all,
aes(x = x, y = y, label = label),
inherit.aes = FALSE, nudge_y = -1,5)
}
else{
mtcars$model <- row.names(mtcars)
p1 <- ggplot(mtcars, aes_string(x = input$lx1, y = input$lx2,key = "model",group = 1))+
# Change the point options in geom_point
geom_point(color = "darkblue") +
# Change the title of the plot (can change axis titles
# in this option as well and add subtitle)
labs(title = "Cross Correlation") +
# Change where the tick marks are
scale_x_continuous(breaks = seq(0, 35, 5)) +
scale_y_continuous(breaks = seq(0, 35, 5)) +
# Change how the text looks for each element
theme(title = element_text(family = "Calibri",
size = 10,
face = "bold"),
axis.title = element_text(family = "Calibri Light",
size = 16,
face = "bold",
color = "darkgrey"),
axis.text = element_text(family = "Calibri",
size = 11))+
theme_bw()+
annotate("text", x = 5, y = 5, label = as.character(input$an))+
# 4. add labels for clicked points
geom_text(data = vals$click_all,
aes(x = x, y = y, label = label),
inherit.aes = FALSE, nudge_y = -1,5)
}
ggplotly(p1,source = "select", tooltip = c("key")) %>%
layout(hoverlabel = list(bgcolor = "white",
font = list(family = "Calibri",
size = 9,
color = "black")))
})
# 5a. reset plotly click event and vals$click_all upon changing plot inputs
observeEvent(c(
input$lx1,
input$lx2
), {
session$sendCustomMessage("resetValue", ".clientValue-plotly_click-select")
vals$click_all <- data.frame(x = numeric(),
y = numeric(),
label = character())
})
}
1. Reset the plotly event input
First, add this to the ui:
js <- HTML(
"Shiny.addCustomMessageHandler('resetValue', function(variableName){
Shiny.onInputChange(variableName, null);
}
);"
)
ui <- fluidPage(
tags$head(tags$script(js)),
...
)
Then, use the message handler in the server:
session$sendCustomMessage("resetValue", ".clientValue-plotly_click-select")
Note, the plotly event data follows this format: '.clientValue-event-source', where event is the type of event (e.g. plotly_click, plotly_hover, etc) and source is specified in the plot where the click event data are coming from.
This method was adapted from this answer. This article is also a useful reference.
2. Reset the reactive dataframe
vals$click_all <- data.frame(x = numeric(),
y = numeric(),
label = character())
3. Use observeEvent to trigger "resets" when plot variables change
observeEvent(c(
input$column_x,
input$column_y
), {
session$sendCustomMessage("resetValue", ".clientValue-plotly_click-select")
vals$click_all <- data.frame(x = numeric(),
y = numeric(),
label = character())
})
Note: you need to add the session argument to your server function, like this:
server <- function(input, output, session) {
...
}
Minimal example
library(shiny)
library(plotly)
library(htmlwidgets)
js <- HTML(
"Shiny.addCustomMessageHandler('resetValue', function(variableName){
Shiny.onInputChange(variableName, null);
}
);"
)
ui <- fluidPage(
# 5b. js to reset the plotly click event
tags$head(tags$script(js)),
fluidRow(column(width = 3,
selectInput("column_x", "X Variable", colnames(mtcars)),
selectInput("column_y", "Y Variable", colnames(mtcars))),
column(width = 9,
plotlyOutput("plot")
)
)
)
server <- function(input, output, session) {
# 1. create reactive values
vals <- reactiveValues()
# 2. create df to store clicks
vals$click_all <- data.frame(x = numeric(),
y = numeric(),
label = character())
# 3. add points upon plot click
observeEvent({event_data("plotly_click", source = "select")}, {
# get clicked point
click_data <- event_data("plotly_click", source = "select")
# check if from correct curve
if(!is.null(click_data) && click_data[["curveNumber"]] == 0) {
# get data for current point
label_data <- data.frame(x = click_data[["x"]],
y = click_data[["y"]],
label = click_data[["key"]],
stringsAsFactors = FALSE)
# add current point to df of all clicks
vals$click_all <- merge(vals$click_all,
label_data,
all = TRUE)
}
})
output$plot <- renderPlotly({
mtcars$model <- row.names(mtcars)
g <- ggplot(mtcars, aes_string(x = input$column_x,
y = input$column_y,
key = "model",
group = 1)) +
geom_point() +
geom_smooth(aes(group = 1)) +
# 4. add labels for clicked points
geom_text(data = vals$click_all,
aes(x = x, y = y, label = label),
inherit.aes = FALSE, nudge_x = 1.5)
ggplotly(g, source = "select", tooltip = c("key"))
})
# 5a. reset plotly click event and vals$click_all upon changing plot inputs
observeEvent(c(
input$column_x,
input$column_y
), {
session$sendCustomMessage("resetValue", ".clientValue-plotly_click-select")
vals$click_all <- data.frame(x = numeric(),
y = numeric(),
label = character())
})
}
shinyApp(ui, server)

Shiny - Plotly output not appearing in viewer

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)

Resources