I've been struggling to add a functional slider input to my ggplot line chart for "number of observations", but I keep getting errors .. The code below works but the plot does not change ( I tried lots of stuff like adding a reactive function or adding input$obs inside ggplot but it still didn't work) .. I really appreciate your help ! Thanks
library(shiny)
library(shinydashboard)
library(readxl)
library(ggplot2)
library(dashboardthemes)
library(shinyWidgets)
library(dplyr)
df=read_excel("MASI.xlsx")
# Define UI for application that draws a histogram
ui <- dashboardPage(
dashboardHeader(title = "Finance Dashboard"),
dashboardSidebar(),
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(
box(
title = "Line chart", status = "primary", solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plot1", height = 250)
),
box(
title = "MASI", status = "primary", solidHeader = TRUE,
"The MASI index (Moroccan All Shares Index) is a stock index that tracks the performance of all
companies listed in the Casablanca Stock Exchange located at Casablanca."
),
box(
title = "Inputs", status = "primary", solidHeader = TRUE, collapsible = TRUE,
sliderInput("obs",
"Number of observations:",
min = 1,
max = length(df$MASI),
value = 50)
),
),
),
setBackgroundColor(
color = "white",
gradient = c("linear", "radial"),
direction = c("bottom", "top", "right", "left"),
shinydashboard = TRUE
)
)
server <- function(input, output) {
output$plot1 <- renderPlot({
ggplot(df,aes(x=Session, y=MASI)) + geom_line( color="darkblue", size=0.7) + theme_bw()
}, bg="transparent")
}
shinyApp(ui, server)
EDIT
Thank you for the kind answer #chemdork123.
I want to add a Date range in addition to the sliderInput. Here's what I did:
library(shiny)
library(shinydashboard)
library(readxl)
library(ggplot2)
library(dashboardthemes)
library(shinyWidgets)
library(dplyr)
df=read_excel("MASI.xlsx")
# Define UI for application that draws a histogram
box_height = "20em"
plot_height = "16em"
ui <- dashboardPage(
dashboardHeader(title = "Finance Dashboard"),
dashboardSidebar(),
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(
box(
title = "Line chart", status = "primary", solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plot1", height = 250)
),
box(
title = "MASI", status = "primary", solidHeader = TRUE,
"The MASI index (Moroccan All Shares Index) is a stock index that tracks the performance of all
companies listed in the Casablanca Stock Exchange located at Casablanca."
),
box(
title = "Inputs", status = "primary", solidHeader = TRUE, collapsible = TRUE,
sliderInput("obs",
"Number of observations:",
min = 1,
max = length(df$MASI),
value = 50),
dateRangeInput("date", strong("Date range"),
start = "2015-01-02", end = "2020-07-17",
min = "2015-01-02", max = "2020-07-17")
),
box(
title = "Line chart", status = "success", solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plot2", height = 250)
),
box(
title = "Return", status = "success", solidHeader = TRUE,
"The relative difference of the MASI index"
),
box(
title = "Inputs", status = "success", solidHeader = TRUE, collapsible = TRUE,
sliderInput("obs",
"Number of observations:",
min = 1,
max = length(df$MASI),
value = 50)
),
),
),
setBackgroundColor(
color = "white",
gradient = c("linear", "radial"),
direction = c("bottom", "top", "right", "left"),
shinydashboard = TRUE
)
)
server <- function(input, output) {
reactive_data <- reactive({
set.seed(8675309) # for some consistent sampling
df <- df[sample(x=1:nrow(df), size = input$obs),]
return(df)
req(input$date)
validate(need(!is.na(input$date[1]) & !is.na(input$date[2]), "Error: Please provide both a start and an end date."))
validate(need(input$date[1] < input$date[2], "Error: Start date should be earlier than end date."))
df %>%
filter(
date > as.POSIXct(input$date[1]) & date < as.POSIXct(input$date[2]
))
})
output$plot1 <- renderPlot({
ggplot(reactive_data(),aes(x=Session, y=MASI)) + geom_line(color="darkblue", size=0.7) + theme_bw()
}, bg="transparent")
output$plot2 <- renderPlot({
ggplot(df,aes(x=Session, y=Return)) + geom_line( color="darkblue", size=0.7) + theme_bw()
}, bg="transparent")
}
shinyApp(ui, server)
Here is a link for the Dataset
Capture
OP. Without your data, it's difficult to give you a clear answer to your particular question, but I can show you how the input$obs slider input control can be used (or any other one for that matter) to filter and provide data for your ggplot() function to display.
Here's a working app that gives you two controls to adjust what data is displayed from the mtcars built-in dataset. The sliderInput() control determines how many rows are sampled from the total mtcars dataset. The selectInput() control allows you to select one or all of the values for mtcars$carb to display in the chart based on the sampled dataset.
You will see the general approach on how to use both inputs reactively is to create a reactive function (called sample_cars()) that is called inside of the renderPlot() function. The reactive function sample_cars() returns a data frame that is used in the ggplot() call.
library(shiny)
library(shinydashboard)
library(ggplot2)
library(dplyr)
library(tidyr)
ui <- dashboardPage(
dashboardHeader(title = "Example App"),
dashboardSidebar(),
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(
box(
title = "Line chart", status = "primary", solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plot1", height = 250)),
box(
title = "Inputs", status = "primary", solidHeader = TRUE, collapsible = TRUE,
sliderInput("obs", "Number of observations:",
min = 1, step = 1, max = nrow(mtcars), value = nrow(mtcars)),
selectInput("carbs", "Select carb to show",
choices = c('All', unique(mtcars$carb))
)
),
)
)
)
server <- function(input, output) {
sample_cars <- reactive({
set.seed(8675309) # for some consistent sampling
df <- mtcars[sample(x=1:nrow(mtcars), size = input$obs),]
if(input$carbs != "All")
df <- df %>% dplyr::filter(carb == input$carbs)
return(df)
})
output$plot1 <- renderPlot({
ggplot(sample_cars(), aes(mpg, disp)) + geom_point() +
labs(title=paste('You selected',input$obs, 'cars\n and to show',input$carbs, 'values of carb!'))
}, bg="transparent")
}
shinyApp(ui, server)
Related
I am trying to have an explanatory image and text box appear after a user presses an action button. Ideally, Id like the box to be centered and directly below the image without too much space in between. Also, I'm curious how to make the box wider for aesthetic purposes.
Here is what my attempt looks like:
Here is my code:
ui <- dashboardPage(
dashboardHeader(title = "Test Test Test"),
dashboardSidebar(disable = T),
dashboardBody(useShinyjs(),
shinyUI(fluidPage(
navbarPage(
"Test",
id = "main_navbar",
tabPanel(
"Test",
fluidRow(align="center",
column(width = 6,
numericInput("age", "Age", 40, min = 18, max = 100, step = 2)
)),
fluidRow(align="center",
actionButton("predict", "Predict")
),
br(),
fluidRow(align="center",
imageOutput("waterfallPlot")
),
shinyjs::hidden(
div(style="text-align: justify",
id = "hiddenbox",
box(
title = "Hidden Box",
status = "primary",
solidHeader = TRUE,
collapsible = TRUE,
uiOutput(outputId = "waterfallDescription")
)
)
)
)
)
))))
server <- function(input, output, session) {
results <- eventReactive(input$predict, {
output <- as.integer(input$age)
output
})
output$waterfallPlot <- renderImage({
# Return a list containing the filename
temp <- results()
list(src = waterfallPlots[1],
contentType = 'image/png'
,width = 400,
height = 300
)
}, deleteFile = FALSE)
observeEvent(input$predict, {
shinyjs::show(id = "hiddenbox")
})
output$waterfallDescription <- renderText({
temp <- results()
HTML(paste0("<p>","bold","</b>", " The waterfall chart to the left explains why your prediction
differs from the average person’s prediction.The average prediction is shown at the bottom.", "</p>", "<p>",
"Each factor that goes into the model is shown in increasing order of impact going up.
For example, a blue bar pointing left means that your input for that feature decreases the model’s
output from the average output by the listed number.", "</p>"))
})
}
shinyApp(ui, server)
library(shiny);
library(shinydashboard)
library(shinyjs)
ui <- dashboardPage(
dashboardHeader(title = "Test Test Test"),
dashboardSidebar(disable = T),
dashboardBody(useShinyjs(),
shinyUI(fluidPage(
navbarPage(
"Test",
id = "main_navbar",
tabPanel(
"Test",
fluidRow(align="center",
column(width = 12,
numericInput("age", "Age", 40, min = 18, max = 100, step = 2)
)),
fluidRow(align="center",
actionButton("predict", "Predict")
),
br(),
fluidRow(align="center",
imageOutput("waterfallPlot", height = "200px")
),
shinyjs::hidden(
div(style="text-align: justify",
id = "hiddenbox",
box(
width = 12,
title = "Hidden Box",
status = "primary",
solidHeader = TRUE,
collapsible = TRUE,
uiOutput(outputId = "waterfallDescription")
)
)
)
)
)
))))
server <- function(input, output, session) {
results <- eventReactive(input$predict, {
output <- as.integer(input$age)
output
})
output$waterfallPlot <- renderImage({
# Return a list containing the filename
temp <- results()
list(src = tempfile(),
contentType = 'image/png'
,width = 400,
height = 300
)
}, deleteFile = FALSE)
observeEvent(input$predict, {
shinyjs::show(id = "hiddenbox")
})
output$waterfallDescription <- renderText({
temp <- results()
HTML(paste0("<p>","bold","</b>", " The waterfall chart to the left explains why your prediction
differs from the average person’s prediction.The average prediction is shown at the bottom.", "</p>", "<p>",
"Each factor that goes into the model is shown in increasing order of impact going up.
For example, a blue bar pointing left means that your input for that feature decreases the model’s
output from the average output by the listed number.", "</p>"))
})
}
shinyApp(ui, server)
You can use width to change box width, from 1-12.
Use height of imageOutput to adjust the gap between image and box.
I want to build an app with the checkbox asking whether to show additional text comments under the figures.
I would like to display set of plots with or without an explanation - this shall be left to the user, whether they need more info or not.
Here are some dummy comments:
#info for box1:
"This is the red histogram"
#info for box2:
"This is the blue histogram"
Here is a dummy app:
library(shiny)
library(shinydashboard)
data <- rnorm(10000, mean=8, sd=1.3)
variable <- "This is the blue histogram"
shinyApp(
ui = dashboardPage(
skin = "black",
dashboardHeader(
title = "Example app",
titleWidth = 300
),
dashboardSidebar(
checkboxInput("show_comment",
label = "Show comment?",
value = FALSE)
),
dashboardBody(
box(title = "First histogram",
status= "warning",
plotOutput("plot1", height=300)
),
box(title = "Second histogram",
status= "warning",
plotOutput("plot2", height=300),
hidden(
div(id='text_div',
verbatimTextOutput("text")))
)
)
),
server = function(input, output) {
output$plot1 <- renderPlot({
hist(data, breaks=40, col="red", xlim=c(2,14), ylim=c(0,800))
})
output$plot2 <- renderPlot({
hist(data, breaks=20, col="blue", xlim=c(2,34), ylim=c(0,1000))
})
observeEvent(input$show_comment, {
toggle('text_div')
output$text <- renderText({ paste0(variable)})
})
}
)
The above code does not work properly - it displays comment no matter if the checkbox is clicked or not. I'd like to make it work, therefore seek for advice here.
I was trying to do it on my own using following hints, to no avail:
How to use shiny actionButton to show & hide text output?
This syntax is too complex for me as I am a beginner with shiny, so I was not able to troubleshoot my problem with hints from this thread:
Show and hide text in modularized shiny app based on actionButton() and shinyJS()
I also tried ths:
Hide/show outputs Shiny R
And here is the attempt of using above hint:
library(shiny)
library(shinydashboard)
data <- rnorm(10000, mean=8, sd=1.3)
variable <- "This is the blue histogram"
shinyApp(
ui = dashboardPage(
skin = "black",
dashboardHeader(
title = "Example app",
titleWidth = 300
),
dashboardSidebar(
checkboxInput("show_comment",
label = "Show comment?",
value = FALSE)
),
dashboardBody(
box(title = "First histogram",
status= "warning",
plotOutput("plot1", height=300)
),
box(title = "Second histogram",
status= "warning",
plotOutput("plot2", height=300),
renderText("text", span(variable))
)
)
),
server = function(input, output) {
output$plot1 <- renderPlot({
hist(data, breaks=40, col="red", xlim=c(2,14), ylim=c(0,800))
})
output$plot2 <- renderPlot({
hist(data, breaks=20, col="blue", xlim=c(2,34), ylim=c(0,1000))
})
observeEvent(input$show_comment, {
# every time the button is pressed, alternate between hiding and showing the plot
toggle("text")
})
}
)
I want to put the comments inside the same box, along with the plot - this is why I am trying to enclose it with the box command. However, if it is impossible - I would be glad of any other solution.
First time I use shinyjs so there might be a better approach. But as I understand it from the docs you first have to add useShinyjs() in your UI code
in order for all other shinyjs functions to work.
Second, there is no need to wrap the div for your comment in hidden(). Third, instead of using observeEvent I followed the example in ?toggle and use an observe where I add the state of your checkbox as the condition to trigger the toggle.
library(shiny)
library(shinydashboard)
library(shinyjs)
data <- rnorm(10000, mean = 8, sd = 1.3)
variable <- "This is the blue histogram"
shinyApp(
ui = dashboardPage(
skin = "black",
dashboardHeader(
title = "Example app",
titleWidth = 300
),
dashboardSidebar(
checkboxInput("show_comment",
label = "Show comment?",
value = FALSE
)
),
dashboardBody(
box(
title = "First histogram",
status = "warning",
plotOutput("plot1", height = 300)
),
box(
title = "Second histogram",
status = "warning",
plotOutput("plot2", height = 300),
div(id = "text_div",
verbatimTextOutput("text")
)
)
),
useShinyjs()
),
server = function(input, output) {
output$plot1 <- renderPlot({
hist(data, breaks = 40, col = "red", xlim = c(2, 14), ylim = c(0, 800))
})
output$plot2 <- renderPlot({
hist(data, breaks = 20, col = "blue", xlim = c(2, 34), ylim = c(0, 1000))
})
observe({
toggle(id = "text_div", condition = input$show_comment)
output$text <- renderText({
paste0(variable)
})
})
}
)
#>
#> Listening on http://127.0.0.1:7437
Help! For the life of me, I can't get values to populate from the server to the infoBox in the UI.
I've tried to define the infoboxes from the server section, but the infoboxes will only appear if I construct them in the UI (as shown below).
The goal is to populate the boxes with filtered data based on user inputs, but I've abandoned this at this stage because I can't even pass a value from the server to the UI infobox here:
infoBox("Participants Trained",
value = renderText("AYval"), # tried every combo here
width = 12,color = "blue", # tried width = NULL
icon = icon("fa-solid fa-people-group"), fill = F)
A value shows when I hardcode a value in "value = ", but none of the render options, renderText, verbatimText, output$AYval, valueTextbox, listen(),react() will get a value that is hard-coded in the server side to show up in this infobox.
To get the dashboard to display boxes, I'm using header = tagList(useShinydashboard()). My guess is this useShinydashboard() is the culprit.
I thought this comment might be relevant:
Your code using lapply and the navbarPage doesn't generate the UI in
the proper namespace, since when using the navbarPage construct your
modules are "one level deeper".
The script:
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyWidgets)
#library(shinyjs)
side_width <- 5
#completing the ui part with dashboardPage
ui <- navbarPage(fluid = TRUE,
theme = shinythemes::shinytheme("flatly"),
collapsible = TRUE,
header = tagList(
useShinydashboard()
),
tabPanel("START"),
tabPanel("Home Dashboard",
value = "Tab1",
# useShinyjs(),
fluidRow(
column(4,
# Selection Input ---------------------------------------------------------
selectInput(inputId = "AY","Academic Year",
multiple = T,
choices = unique(INDGEN$AcademicYear),
selected = unique(INDGEN$AcademicYear)
)),
column(4,
selectInput(inputId = "State","Select State",
choices = c("State","States"))),
column(4,
selectInput(inputId = "Program","Select Program",
choices = c("Program","Programs")))
),
fluidRow(column(12,
box(width = 4,
infoBox("Who?",
width = 12,color = "blue",
fill = F)
),
box(width = 4,
infoBox("Where?", width = 12,color = "blue",
fill = F)
),
box(width = 4,
infoBox("What?", width = 12,color = "blue",
fill = F))
)),
# UI Box R1 ---------------------------------------------------------------
fluidRow(column(12,
box(width = 4,
# uiOutput(infoBoxOutput("BOX1",width = NULL)),
infoBox("Participants Trained", value =
renderText("AYval"),
width = 12,color = "blue",
icon = icon("fa-solid fa-people-group"), fill = F)
),box(width = 4,
infoBox("Training Sites", nrow(data), width = 12,color = "blue",
icon = icon("fa-solid fa-school"), fill = F)
),box(width = 4,
infoBox("Training Programs Offered", nrow(data), width = 12,color = "blue",
icon = icon("fa-solid fa-book-open-reader"), fill = F))
)),
server <- function(input, output,session) {
output$AYval <- renderText({
textInput(13)
})
output$BOX1 <- renderInfoBox({
infoBox(title = "Participants Trained",
value = 13,
width = NULL,color = "blue",
icon = icon("fa-solid fa-people-group"), fill = T)
})
}#Server End
shinyApp(ui = ui,server = server,options = list(height = 1440))
Notice the "participant trained" box is empty. That's because that value isn't hard-coded. The rest are.
Here's a small reproducible example of how to change the value contents dynamically:
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyWidgets)
data(iris)
ui <- navbarPage(
fluid = TRUE,
theme = shinythemes::shinytheme("flatly"),
collapsible = TRUE,
header = tagList(
useShinydashboard()
),
tabPanel("START"),
tabPanel(
title = "Home Dashboard",
value = "Tab1",
selectInput("column",
label = "Select a column",
choices = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
),
box(
width = 4,
infoBoxOutput("test")
)
)
)
server <- function(input, output, session) {
iris_sum <- reactive({
sum(iris[input$column])
})
output$test <- shinydashboard::renderInfoBox({
infoBox(
title = "Where?",
value = iris_sum(),
width = 12,
color = "blue",
fill = F
)
})
}
shinyApp(ui, server)
I am in the process of creating a shiny app for a process at work and am struggling to figure something out on the UI side of the app. I would like to display a data table next to a sidebar menu containing options for the app. The issue is that when I do so, the data table is pushed down below the sidebar panel instead of beside it (see the original data tab).
I found a work around as seen in the suggested tab, but that comes with its own issues. I need to be able to lock the column headers while scrolling through the app and when the data table is inside the box element, I am unable to find a way to do so.
Here is the code to a simplified version of the app.
library(shiny)
library(lubridate)
library(tidyverse)
library(DT)
library(shinydashboard)
library(shinythemes)
library(sortable)
library(reactlog)
ui<- dashboardPage(
#this gives you the name displayed on the tab
dashboardHeader(title = "HHS Resin Purchasing 0.99"),
#this gives you your sidebar (page) options
dashboardSidebar(
sidebarMenu(
menuItem("Original Data", tabName = "original"),
menuItem("Suggested", tabName = "suggested")
)
),
#this is the body of the webpages
dashboardBody(
#this gives you the body options that are displayed on every page
sidebarPanel(width = 2,
h2("Menu Options"),
h4(strong("Upload Data:")),
fileInput("file", "Data", buttonLabel = "Upload..."),
textInput("delim", "Delimiter (leave blank to guess)", ""),
numericInput("skip", "Rows to skip", 0, min = 0),
h4(strong("User Options:")),
selectInput("plant", "Select a Plant", choices =
c("All")),
dateInput("latest_date", "Select the latest W_LEAD date in the data",
value = Sys.Date()),
numericInput("avg_multiple", "Multiple of Daily Useage for Cuttoff",21, min = 1, max = 50),
h4(strong("Download Options:")),
actionButton("complete_orders", "Analysis for plant orders complete"),
actionButton("complete_checks", "Mid month check complete"),
downloadButton("downloadData1", label = "Download Suggested Orders...", class = "btn-block"),
downloadButton("downloadData2", label = "Download Flags...", class = "btn-block"),
downloadButton("downloadData3", label = "Download Full Suggested Orders Data...", class = "btn-block")
),
#This is the actual data that fills those page options listed above
tabItems(
tabItem(tabName = "original",
DT::dataTableOutput(outputId = "preview1")
),
tabItem(tabName = "suggested",
box(title = "Suggested Orders",width = 9, status = "primary", height = "auto",
solidHeader = T, dataTableOutput("preview2"), style = "max-height:800px; overflow-y: scroll;overflow-x: scroll;")
)
)
)
)
server <- function(input, output) {
output$preview1 <- renderDataTable({
DT::datatable(iris, options = list(searching = T, pageLength = 20, lengthMenu = c(5,10,15, 20))
})
output$preview2 <- renderDataTable({
DT::datatable(iris, options = list(searching = T, pageLength = 20, lengthMenu = c(5,10,15, 20))
})
}
shinyApp(ui, server)
Help in fixing either of the issues outlined above would be very appreciated! Thanks in advance.
I think using the column() function will support your first question of the datatable moving under the sidebar sidebarPanel. Please see example below.
I think the second request of freezing the row header in the datatable can be resolved with the advice found at Freezing header and first column using data.table in Shiny
library(shiny)
library(lubridate)
library(tidyverse)
library(DT)
library(shinydashboard)
library(shinythemes)
library(sortable)
library(reactlog)
ui<- dashboardPage(
#this gives you the name displayed on the tab
dashboardHeader(title = "HHS Resin Purchasing 0.99"),
#this gives you your sidebar (page) options
dashboardSidebar(
sidebarMenu(
menuItem("Original Data", tabName = "original"),
menuItem("Suggested", tabName = "suggested")
)
),
#this is the body of the webpages
dashboardBody(
#this gives you the body options that are displayed on every page
fluidRow(
column(width = 2,
sidebarPanel(width = 2,
h2("Menu Options"),
h4(strong("Upload Data:")),
fileInput("file", "Data", buttonLabel = "Upload..."),
textInput("delim", "Delimiter (leave blank to guess)", ""),
numericInput("skip", "Rows to skip", 0, min = 0),
h4(strong("User Options:")),
selectInput("plant", "Select a Plant", choices =
c("All")),
dateInput("latest_date", "Select the latest W_LEAD date in the data",
value = Sys.Date()),
numericInput("avg_multiple", "Multiple of Daily Useage for Cuttoff",21, min = 1, max = 50),
h4(strong("Download Options:")),
actionButton("complete_orders", "Analysis for plant orders complete"),
actionButton("complete_checks", "Mid month check complete"),
downloadButton("downloadData1", label = "Download Suggested Orders...", class = "btn-block"),
downloadButton("downloadData2", label = "Download Flags...", class = "btn-block"),
downloadButton("downloadData3", label = "Download Full Suggested Orders Data...", class = "btn-block")
)
),
#This is the actual data that fills those page options listed above
column(width = 6,
tabItems(
tabItem(
tabName = "original",
DT::dataTableOutput("preview1",
options = list(dom = 't',
scrollX = TRUE,
paging=FALSE,
fixedHeader=TRUE,
fixedColumns = list(leftColumns = 1, rightColumns = 0)))
),
tabItem(tabName = "suggested",
box(title = "Suggested Orders",width = 9, status = "primary", height = "auto",
solidHeader = T, dataTableOutput("preview2"), style = "max-height:800px; overflow-y: scroll;overflow-x: scroll;")
)
)
)
)
)
)
server <- function(input, output) {
output$preview1 <- renderDataTable({
DT::datatable(iris, options = list(searching = T, pageLength = 20, lengthMenu = c(5,10,15, 20)))
})
output$preview2 <- renderDataTable({
DT::datatable(iris, options = list(searching = T, pageLength = 20, lengthMenu = c(5,10,15, 20)))
})
}
shinyApp(ui, server)
I am trying to create scatter plot outputs in the shiny dashboard. I have similar datasets for several years, and I want to plot according to chosen variables and year. Datasets file name is Y96Total8.rda, Y97Total8.rda... Datasets name is Total (data.table).
Unfortunately, I can't load the dataset in a true way to plot the results, and I have the error "non-numeric argument to mathematical function" in plot tab.
If anyone has any suggestions on how to produce this plot using the shiny dashboard it would be much appreciated.
I have attached the code.
library(shiny)
library(shinydashboard)
library(data.table)
library(ggplot2)
library(plotly)
library(DT)
header <- dashboardPage(
skin = "green",
dashboardHeader(title = "TEST"),
dashboardSidebar(sidebarMenu(
dir = "ltr",
align = "right",
menuItem("Correlation", tabName = "Correlation", icon = icon("users"))
)),
dashboardBody(load(file = "data/Test.rda"),
dir = "ltr",
tabItems(
tabItem(tabName = "Correlation",
fluidRow(tabsetPanel(
tabPanel(
"Inputs",
box(
status = "danger",
solidHeader = TRUE,
width = 6,
title = "Food Expenditures Per",
sliderInput(
inputId = "Food_Expenditures_Per2",
label = "Food Expenditures",
min = 0,
max = 30000000,
value = c(1000000, 10000000)
)
),
box(
status = "danger",
solidHeader = TRUE,
title = "Total Expenditures Per",
width = 6,
sliderInput(
inputId = "Total_Exp_Month_Per2",
label = "Total Expenditures Per",
min = 0,
max = 100000000,
value = c(1000000, 30000000)
)
),
box(
status = "info",
solidHeader = TRUE,
title = "First Variable",
width = 6,
selectInput(
"Var1",
"First Variable",
list("FoodExpenditure_Per", "Total_Exp_Month_Per"),
selected =
"FoodExpenditure_Per"
)
),
box(
status = "info",
solidHeader = TRUE,
title = "Second Variable",
width = 6,
selectInput(
"Var2",
"Second Variable",
list("FoodExpenditure_Per", "Total_Exp_Month_Per"),
selected =
"Total_Exp_Month_Per"
)
),
box(
status = "info",
solidHeader = TRUE,
title = "Year",
width = 6,
selectInput(
inputId = "slcT2Year3",
label = "Year",
choices =
list(1390, 1391, 1392, 1393,
1394, 1395, 1396, 1397),
selected =
1396
)
),
box(
status = "info",
solidHeader = TRUE,
title = "Add line of best fit",
width = 6,
checkboxInput("fit", "Add line of best fit")
),
),
tabPanel(
"Plot"
,
box(
status = "info",
solidHeader = TRUE,
width = 700,
height = 450,
plotOutput("scatterplot", width =
600, height = 400)
,
downloadButton("downloadPlot3", "Download")
)
)
)))
))
)
app_server <- function(input, output, session) {
##################### Scatter Plot #########################
output$scatterplot <- renderPlot({
y <- input$slcT2Year3
fn3 <- paste0("data/Y", substr(y, 3, 4), "Total8.rda")
load(fn3)
Total <- subset(
Total,
FoodExpenditure_Per >= input$Food_Expenditures_Per2[1] &
FoodExpenditure_Per <= input$Food_Expenditures_Per2[2] &
Total_Exp_Month_Per >= input$Total_Exp_Month_Per2[1] &
Total_Exp_Month_Per <= input$Total_Exp_Month_Per2[2]
)
p <- ggplot(Total, aes(input$Var1, input$Var2)) +
geom_point() +
scale_x_log10()
if (input$fit == TRUE) {
p <- p + geom_smooth(method = "lm")
}
p
})
session$onSessionEnded(function() {
stopApp()
# q("no")
})
}
shinyApp(header, app_server)
Image of the error:
Your ggplot call should be changed to
p <- ggplot(Total, aes(Total[[input$Var1]], Total[[input$Var2]]))