I would like to be able to display a multi-line graph with an imported csv. CSV files contain time series. On import, I would like to be able to choose, knowing that the name of the fields can change according to the CSV, the field representing the X and the one of Y, and define the field containing the ID which will create the various lines. Something like this :
For now, I have this but it's completly wrong
# ui.R
library(shiny)
library(shinydashboard)
library(ggplot2)
shinyUI(
dashboardPage(
dashboardHeader(title ="Sen2extract"),
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("Chart", tabName = "chart")
)
),
dashboardBody(
tabItem(tabName = "chart",
box(
width = 12, collapsible=FALSE,
fileInput(inputId = "csv_chart", label = "Upload your CSV", multiple = FALSE,
accept = c(".csv", "text/csv", "text/comma-separated-values,text/plan"), width = "300px"),
selectInput("X", label = "Field X :", choices = list("Choice 1" = "")),
selectInput("Y", label = "Field Y :", choices = list("Choice 1" = "")),
selectInput("group", label = "Group by :", choices = list("Choice 1" = ""))
),
box(plotOutput("plot"), width = 12)
)
)
)
)
# server.R
library(shiny)
library(shinydashboard)
library(ggplot2)
shinyServer(function(input, output, session){
output$plot = renderPlot({
data <- read.csv(file = input$csv_chart)
ggplot(data) +
geom_line(mapping = aes(x = input$X, y = input$Y)) +
labs (x = "Years", y = "", title = "Index Values")
})
})
there were several issues with your code and I have a working version below.
The main issue was that you have to read your data within reactive() and then update the selection. Also, to have multiple lines in your graph, you have to add what to group on in ggplot when you define the mapping in aes or in this case aes_string. I chose color as this gives multiple lines colored according to different groups in the chosen column.
library(shiny)
library(shinydashboard)
library(tidyverse)
ui <- dashboardPage(
dashboardHeader(title ="Sen2extract"),
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("Chart", tabName = "chart")
)
),
dashboardBody(
tabItem(tabName = "chart",
box(
width = 12, collapsible=FALSE,
fileInput(inputId = "csv_chart", label = "Upload your CSV",
multiple = FALSE,
accept = c(".csv",
"text/csv",
"text/comma-separated-values,text/plan"),
width = "300px"),
selectInput("X", label = "Field X:", choices = "Pending Upload"),
selectInput("Y", label = "Field Y:", choices = "Pending Upload"),
selectInput("group", label = "Group by:", choices = "Pending Upload")
),
box(plotOutput("plot"), width = 12)
)
)
)
server <- function(input, output, session){
data <- reactive({
req(input$csv_chart)
infile <- input$csv_chart
if (is.null(infile))
return(NULL)
df <- read_csv(infile$datapath)
updateSelectInput(session, inputId = 'X', label = 'Field X:',
choices = names(df), selected = names(df)[1])
updateSelectInput(session, inputId = 'Y', label = 'Field Y:',
choices = names(df), selected = names(df)[2])
updateSelectInput(session, inputId = 'group', label = 'Group by:',
choices = names(df), selected = names(df)[3])
return(df)
})
output$plot <- renderPlot({
ggplot(data()) +
geom_line(mapping = aes_string(x = input$X, y = input$Y, color=input$group)) +
labs(x = "Years", y = "", title = "Index Values")
})
}
shinyApp(ui = ui, server = server)
Related
I recently started using Shiny and I need help with shiny dashboard errors. I am trying to build an app using Shiny Dashboard, But I keep getting errors: "Error in tagAssert(sidebar, type = "aside", class = "main-sidebar") :
object 'sidebar' not found"
Can Someone help me fix the error??
Thanks in Advance
library(shiny)
library(shinydashboard)
library(DT)
library(tidyverse)
library(plotly)
covid <- read.csv("covid.csv")
covid_deaths <- read.csv("COVID_DEATHS_UK.csv")
noncovid_deaths <- read.csv("NON_COVID_DEATHS_UK.csv")
title <- tags$a(href='https://ourworldindata.org/covid-vaccinations?country=OWID_WRL',
'COVID 19 Vaccinations')
function(request){
sidebar <- dashboardSidebar(
hr(),
sidebarMenu(id="tabs",
menuItem("Global COVID data",
menuSubItem("COVID vaccinations: Deaths Vs All variable", tabName = "Dashboard"),
selectInput("location", "1. Select a country",
choices = covid$location, selectize = TRUE, multiple = FALSE),
menuSubItem("Scatterplot", tabName = "Scatterplot", icon = icon("line-chart")),
menuSubItem("Regression", tabName = "Regression", icon = icon("cog")),
menuSubItem("Multicollinearity", tabName = "Multicollinearity", icon = icon("line-chart")),
menuSubItem("Summary", tabName = "Summary", icon = icon("file-o-text")),
menuSubItem("DataTable", tabName = "DataTable", icon = icon("table"), selected=TRUE)
),
menuItem("COVID_Deaths", tabName = "COVID Deaths", icon = icon("line-chart")),
menuItem("NonCOVID_Deaths", tabName = "Non COVID Deaths", icon = icon("line-chart"))
)
)
body <- dashboardBody(
tabItems(
tabItem(tabName = "Scatterplot",
fluidRow(
column(width = 6,
tabPanel("Scatterplot", plotlyOutput("scatterplot"),
verbatimTextOutput("correlation")),
tabPanel(helpText("Select variables for scatterplot"),
selectInput(inputId = "y", label = "Y-axis:",
choices = c("total_deaths", "new_deaths"),
selected = "Deaths"),
br(),
selectInput(inputId = "x", label = "X-axis:",
choices = names(subset(covid,select = -c(total_deaths,new_deaths,
iso_code, continent,date,location), na.rm =TRUE)),
selectize = TRUE,
selected = "Comparator variables")
))))),
tabItems(
tabItem(tabName = "Regression",
fluidRow(
column(width = 6,
tabPanel(verbatimTextOutput(outputId = "regsum"),
verbatimTextOutput(outputId = "indprint"),
verbatimTextOutput(outputId = "depprint")),
tabPanel(helpText("Select input for Independent variables"),
selectInput(inputId = "indvar", label = "Independent Variable", multiple = TRUE,
choices = list("total_cases", "total_vaccinations", "people_fully_vaccinated", "total_boosters","stringency_index",
"population_density", "aged_65_older","gdp_per_capita","extreme_poverty", "cardiovasc_death_rate", "diabetes_prevalence", "handwashing_facilities", "life_expectancy","human_development_index")),
helpText("Select input for dependent variables"),
selectInput(inputId = "depvar", label = "Dependent variable", multiple = FALSE,
choices = list("total_deaths","new_deaths","new_cases")))
)))),
tabItems(
tabItem(tabName = "Multicollinearity",
fluidRow(
tabPanel(img(src="Multicollinearity.png"))))),
tabItems(
tabItem(tabName = "Summary",
fluidRow(tabPanel(
verbatimTextOutput("summary")
)))),
tabItems(
tabItem(tabName = "DataTable",
fluidRow(tabPanel(DTOutput("dataset")),
tabPanel(helpText("Select the Download Format"),
radioButtons("type", "4. Format type:",
choices = c("Excel (csv)", "Text(tsv)", "Doc")),
br(),
helpText("Click on the download button to download dataset"),
downloadButton("downloadData", "Download"))))),
tabItems(tabItem(tabName = "COVID Deaths",
fluidRow(tabPanel(plotlyOutput("hist1")),
tabPanel(helpText("Select Variables for a COVID deaths"),
selectInput(inputId = "Yaxis", label = "yaxis:",
choices = names(subset(covid_deaths, select = -c(Week_number,Week_ending)))))))),
tabItems(tabItem(tabName = "NonCOVID Deaths",
fluidRow(tabPanel(plotlyOutput("hist2")),
tabPanel(helpText("Select Variables for a NOn- COVID deaths"),
selectInput(inputId = "ya", label = "Yaxis:",
choices = names(subset(noncovid_deaths, select = -c(Week_number,Week_ending))))))))
)
}
ui <- dashboardPage(skin = "black",
dashboardHeader(title = title),
sidebar,body)
server <- function(input, output, session) {
output$location <- renderPrint({
locationfilter <- subset(covid, covid$location == input$location)
})
output$summary <- renderPrint({
summary(covid)
})
datasetinput <- reactive({covid})
fileExt <- reactive({
switch(input$type,
"Excel (csv)" = "csv", "Text (tsv)" = "tsv", "Doc" = "doc")
})
output$dataset <- renderDT(
covid, options = list(
pageLength = 50,
initComplete = JS('function(setting, json) { alert("done"); }')
)
)
output$downloadData <- downloadHandler(
filename = function(){
paste("covid", fileExt(),sep = ".")
},
content = function(file){
sep <- switch(input$type,
"Excel (csv)" = ",", "Text (tsv)" = "\t", "Doc" = " ")
write.table(datasetinput(), file, sep = sep, row.names = FALSE)
}
)
output$scatterplot <- renderPlotly({
#ggplot(subset(covid, covid$location == input$location),aes(y= input$y,x=input$x))+geom_point()
ggplotly(ggplot(subset(covid, covid$location == input$location),
aes(y = .data[[input$y]], x = .data[[input$x]],col = factor(stringency_index)))+
geom_smooth()+geom_point()+labs(col ="Stringency Index"))
})
output$correlation <- renderText({
x <- covid[covid$location == input$location, input$x]
y <- covid[covid$location == input$location, input$y]
xy = data.frame(x,y)
xy = xy[complete.cases(xy),]
var(xy)
cor(xy,method = 'pearson')
})
output$hist1 <- renderPlotly({
ggplotly(ggplot(covid_deaths, aes(x=Week_number, y= .data[[input$Yaxis]]))+
geom_point()
)
})
output$hist2 <- renderPlotly({
ggplotly(ggplot(noncovid_deaths, aes(x=Week_number, y= .data[[input$ya]]))+
geom_point()
)
})
lm1 <- reactive({lm(reformulate(input$indvar, input$depvar), data = subset(covid, covid$location == input$location))})
output$depPrint <- renderPrint({input$depvar})
output$indPrint <- renderPrint({input$indvar})
output$regsum <- renderPrint({summary(lm1())})
}
# Shiny dashboard
shiny::shinyApp(ui, server)
I am creating a shiny app with some tabs and I am using the shinycssloaders package in order to show a spinner AFTER pressing the actionButton. I saw this post because I was having the same problem... I followed the solution that it was given to the post, but as I my app is different (it has tabPanels, it doesn't work properly, the spinner still apears).
For example, if you click on "Show the plot" in the first tab (selection) and then you want to want to do the log2 transformation o calculate the square root (3rd tab, calculations), before clicking the actionButton the spinner appears and the plot updates. It happens the same when you want to change the titles (2nd tab).
Does anyone know how to fix it?
Thanks very much in advance
The code:
library(shiny)
library(magrittr)
library(DT)
library(ggplot2)
library(shinycssloaders)
new_choices <- setNames(names(mtcars), names(mtcars))
ui <- fluidPage(
# Application title
titlePanel("My shiny app"),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel("Selection",
selectInput("x_axis", "Choose x axis",
choices = new_choices),
selectInput("y_axis", "Choose y axis",
choices = new_choices),
hr(),
),
tabPanel("Titles",
hr(),
textInput(inputId = "title", "You can write the title:", value = "This is the title"),
textInput(inputId = "xlab", "You can re-name the x-axis:", value = "x-axis...."),
textInput(inputId = "ylab", "You can re-name the y-axis:", value = "y-axis ...."),
),
tabPanel("Calculations",
hr(),
checkboxInput("log2", "Do the log2 transformation", value = F),
checkboxInput("sqrt", "Calculate the square root", value = F),
)
),
actionButton(inputId = "drawplot", label = "Show the plot")
),
# Show a plot of the generated distribution
mainPanel(
# plotOutput("plot")
uiOutput("spinner"),
)
)
)
server <- function(input, output, session) {
data <- reactive({
mtcars
})
filtered_data <- reactive({
data <- data()
if(input$log2 == TRUE){
data <- log2(data+1)
}
if(input$sqrt == TRUE){
data <- sqrt(data)
}
return(data)
})
observeEvent(input$drawplot, {
output$spinner <- renderUI({
withSpinner(plotOutput("plot"), color="black")
})
output$plot <- renderPlot({
Sys.sleep(3)
ggplot() +
geom_point(data = filtered_data(),
aes_string(x = input$x_axis, y = input$y_axis)) +
xlab(input$xlab) +
ylab(input$ylab) +
ggtitle(input$title)
})
})
}
shinyApp(ui, server)
Is it OK like this? I'm not sure to understand all your requirements. To avoid the spinner at the start-up, I use a conditionalPanel. In the server code, I did some changes. It is not recommended to define some output inside an observer.
library(shiny)
library(magrittr)
library(ggplot2)
library(shinycssloaders)
new_choices <- setNames(names(mtcars), names(mtcars))
ui <- fluidPage(
# Application title
titlePanel("My shiny app"),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel(
"Selection",
selectInput("x_axis", "Choose x axis",
choices = new_choices),
selectInput("y_axis", "Choose y axis",
choices = new_choices),
hr(),
),
tabPanel(
"Titles",
hr(),
textInput(inputId = "title", "You can write the title:", value = "This is the title"),
textInput(inputId = "xlab", "You can re-name the x-axis:", value = "x-axis...."),
textInput(inputId = "ylab", "You can re-name the y-axis:", value = "y-axis ...."),
),
tabPanel(
"Calculations",
hr(),
checkboxInput("log2", "Do the log2 transformation", value = F),
checkboxInput("sqrt", "Calculate the square root", value = F),
)
),
actionButton(inputId = "drawplot", label = "Show the plot")
),
# Show a plot of the generated distribution
mainPanel(
conditionalPanel(
condition = "input.drawplot > 0",
style = "display: none;",
withSpinner(plotOutput("plot"))
)
)
)
)
server <- function(input, output, session) {
data <- reactive({
mtcars
})
filtered_data <- reactive({
data <- data()
if(input$log2 == TRUE){
data <- log2(data+1)
}
if(input$sqrt == TRUE){
data <- sqrt(data)
}
return(data)
})
gg <- reactive({
ggplot() +
geom_point(data = filtered_data(),
aes_string(x = input$x_axis, y = input$y_axis)) +
xlab(input$xlab) +
ylab(input$ylab) +
ggtitle(input$title)
}) %>%
bindEvent(input$drawplot)
output$plot <- renderPlot({
Sys.sleep(3)
gg()
})
}
shinyApp(ui, server)
You need to isolate the expressions that you don't want to trigger the rendering event inside renderPlot
library(shiny)
library(magrittr)
library(DT)
library(ggplot2)
library(shinycssloaders)
new_choices <- setNames(names(mtcars), names(mtcars))
ui <- fluidPage(
# Application title
titlePanel("My shiny app"),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel("Selection",
selectInput("x_axis", "Choose x axis",
choices = new_choices),
selectInput("y_axis", "Choose y axis",
choices = new_choices),
hr(),
),
tabPanel("Titles",
hr(),
textInput(inputId = "title", "You can write the title:", value = "This is the title"),
textInput(inputId = "xlab", "You can re-name the x-axis:", value = "x-axis...."),
textInput(inputId = "ylab", "You can re-name the y-axis:", value = "y-axis ...."),
),
tabPanel("Calculations",
hr(),
checkboxInput("log2", "Do the log2 transformation", value = F),
checkboxInput("sqrt", "Calculate the square root", value = F),
)
),
actionButton(inputId = "drawplot", label = "Show the plot")
),
# Show a plot of the generated distribution
mainPanel(
# plotOutput("plot")
uiOutput("spinner"),
)
)
)
server <- function(input, output, session) {
data <- reactive({
mtcars
})
filtered_data <- reactive({
data <- data()
if(input$log2 == TRUE){
data <- log2(data+1)
}
if(input$sqrt == TRUE){
data <- sqrt(data)
}
return(data)
})
observeEvent(input$drawplot, {
output$spinner <- renderUI({
withSpinner(plotOutput("plot"), color="black")
})
output$plot <- renderPlot({
Sys.sleep(3)
ggplot() +
geom_point(data = isolate(filtered_data()),
aes_string(x = isolate(input$x_axis), y = isolate(input$y_axis))) +
xlab(isolate(input$xlab)) +
ylab(isolate(input$ylab)) +
ggtitle(isolate(input$title))
})
})
}
shinyApp(ui, server)
Read more about shiny reactivity and isolation: https://shiny.rstudio.com/articles/isolation.html
The process_map() function in the server in the R shiny script creates the diagram image as below. My requirement is that there are two attributes "FUN" and "units" that are part of the performance() function. They have standard four values each that are available in the ui code below under PickerInput ID's Case4 and Case5. Currently, I am hard coding the value to create the map, can you help me to use the id's in the server code and make it dynamic such that when I select the value in the PickerInput, the formula fetches the value directly. Thanks and please help.
library(shiny)
library(shinydashboard)
library(bupaR)
library(processmapR)
library(lubridate)
library(dplyr)
library(edeaR)
library(shinyWidgets)
library(DiagrammeR)
ui <- dashboardPage(
dashboardHeader(title = "Diagram Plot",titleWidth = 290),
dashboardSidebar(width = 0),
dashboardBody(
tabsetPanel(type = "tab",
tabPanel("Overview", value = 1,
box(
column(1,
dropdown(
pickerInput(inputId = "resources",
label = "",
choices = c("Throughput Time"),
choicesOpt = list(icon = c("fa fa-bars",
"fa fa-bars",
"fa fa-safari")),
options = list(`icon-base` = "")),
circle = FALSE, status = "primary", icon = icon("list", lib = "glyphicon"), width = "300px"
),
conditionalPanel(
condition = "input.resources == 'Throughput Time' ",
tags$br(),
tags$br(),
tags$br(),
dropdown(
pickerInput(inputId = "Case4",
label = "Select the Process Time Summary Unit",
choices = c("min","max","mean","median"), options = list(`actions-box` = TRUE),
multiple = F),
circle = FALSE, status = "primary", icon = icon("eye-close", lib = "glyphicon"), width = "300px"
),
tags$br(),
tags$br(),
tags$br(),
dropdown(
pickerInput(inputId = "Case5",
label = "Select the Process Time Unit",
choices = c("mins","hours","days","weeks"), options = list(`actions-box` = TRUE),
multiple = F, selected = "days"),
circle = FALSE, status = "primary", icon = icon("eye-close", lib = "glyphicon"), width = "300px"
))),
title = "Process Map",
status = "primary",height = "575", width = "500",
solidHeader = T,
column(10,grVizOutput("State")),
align = "left")
),
id= "tabselected"
)))
server <- function(input, output) {
output$State <- renderDiagrammeR(
{
if(input$resources == "Throughput Time")
patients %>% process_map(performance(FUN = mean,units = "days"))
else
return()
})}
shinyApp(ui, server)
test this:
output$State <- renderDiagrammeR({
if(input$resources == "Throughput Time")
{
if(input$Case4=="mean"){
patients %>% process_map(performance(FUN = mean,units = input$Case5))}
else if(input$case4=="min"){
patients %>% process_map(performance(FUN = min,units = input$Case5))
}else if(input$case4=="max"){
patients %>% process_map(performance(FUN = max ,units = input$Case5))
}else{
patients %>% process_map(performance(FUN = median ,units = input$Case5))
}
}else
return()
})
or you can use this:
patients %>%
process_map(performance(FUN = eval(parse(text=input$Case4)) ,units = input$Case5))
enjoy;)
here is a sample:
library(shiny)
ui <- fluidPage(
selectInput(inputId = "func", label = "Choose The Function", choices = c("mean", "sum", "median"))
,
textOutput("text")
)
server <- function(input, output, session) {
main_data <- reactive({
data.frame(a= rnorm(100), b=rnorm(100) )
})
output$text <- renderText({
df <- main_data()
apply(df,2, FUN = eval(parse(text=input$func)) )
})
}
shinyApp(ui = ui, server = server)
You could use do.call to call a function from its name, see the example below. You can add arguments by adding them in the list in the do.call function, e.g. list(x,units=input$Case5).
library(shiny)
x=c(1,2,3,4,5,6,7)
ui <- fluidPage(
selectInput('select','Select Function: ', choices=c('mean','max','min','median')),
textOutput('text')
)
server <- function(input,output)
{
output$text <- renderText({
result = do.call(input$select, list(x))
paste0('The ', input$select, ' of [', paste(x,collapse=', '),'] is ', result)
})
}
shinyApp(ui,server)
Hope this helps!
I have been working on this for more than 6 hours today, and I know it's a simple issue, but I can't figure it out. What I want is to input a file, and then be able to use multiple selectInput dropdown menus to change the output on the ggplot. Here is what I have so far:
UI:
ui = dashboardPage(
dashboardHeader(title = "Apple Financials"),
dashboardSidebar(
fileInput("file1", label = "Upload SAS Data:", accept = ".sas7bdat"),
selectInput("x", label = "X-Axis Variable", choices = c("Sales", "Cash", "Assets", "Profits", "R&D", "SG&A")),
selectInput("y", label = "Y-Axis Variable", choices = c("Sales", "Cash", "Assets", "Profits", "R&D", "SG&A"), selected = "R&D"),
selectInput("scale", label = "Choose the Scale:", choices = c("Levels", "Log 10")),
radioButtons("model", label = "Choose the Model:", choices = c("Linear Model", "LOESS", "Robust Linear", "None"), selected = "LOESS"),
checkboxInput("ribbon", label = "Standard Error Ribbon", value = TRUE),
conditionalPanel(
condition = "input.model == 'LOESS'",
sliderInput("span", label = "Span for LOESS", min = 0, max = 1, value = .75)
)
),
dashboardBody(
box(width = NULL, height = 415, plotOutput("plots"))
)
)
Server:
server = function(input, output) {
observe({
data = input$file1
if(is.null(data))
return(NULL)
df = read_sas(data$datapath)
output$plots = renderPlot({
ggplot(df, aes(x = input$x, y = input$y)) +
geom_line()
})
})
}
As the input is a string, we need aes_string in ggplot
server = function(input, output) {
observe({
data = input$file1
if(is.null(data))
return(NULL)
df = read_sas(data$datapath)
output$plots = renderPlot({
ggplot(df, aes_string(x = input$x, y = input$y)) +
geom_line()
})
})
}
shinyApp(ui, server)
NOTE: For demonstration, we are uploading a csv file instead of SAS file
I have solved this programmed but while changing input I am unable to find output change as a table please any one can help me using R shiny code
I have solve the error but it's still showing only
library(shiny)
library(DT)
bcl <- read.csv("R-D.csv", stringsAsFactors = FALSE)
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
radioButtons("TYPE.OF.DATA","View data by:", choices = c("NP", "CR", "AN"), inline = TRUE, selected = "NP"),
tags$hr(),
radioButtons(" LINE.OF.BUSINESS ","View data by:" ,choices = c("AF", "HL"), inline = TRUE, selected = "AF"),
tags$hr(),
selectInput("typeInput6", " APPLICATION ",
choices = c("TERADATA"),
selected = "TERADATA"),
tags$hr(),
radioButtons( "DatabaseName","View data by:",choices = c("DW_re", "DW_np", "DW_AN"), inline = TRUE, selected = "DW_re")
),
mainPanel(
DT::dataTableOutput("table")
)
)
))
server <- shinyServer(function(input, output,session) {
observe({
if(input$bcl == "TYPE.OF.DATA"){
choices = c("NP", "CR", "AN")
firstchoice = "NP"
label = "DATA TYPE:"
}else{
choices = c("DW_re", "DW_np", "DW_AN")
firstchoice = "DW_re"
label = "NAME:"
}
updateSelectInput(session, "bcl", label = label, choices = choices, selected = firstchoice)
})
data <- reactive({
data = switch(input$bcl,
"NP" = NP, "CR" = CR, "AN" = AN,
"DW_re" = DW_re, "DW_np" = DW_np, "DW_AN" = DW_AN
)
})
output$table <- DT::renderDataTable({
datatable(data())
})
})
shinyApp(ui=ui,server=server)