I'm trying to create a shiny app that imports different csv's and create plots using for example the package pROC.
library(shiny)
library(datasets)
ui <- shinyUI(fluidPage(
titlePanel("Column Plot"),
tabsetPanel(
tabPanel("Upload File",
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
tags$br(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"')
),
mainPanel(
tableOutput('contents')
)
)
),
tabPanel("First Type",
pageWithSidebar(
headerPanel('My First Plot'),
sidebarPanel(
selectInput('xcol', 'X Variable', ""),
selectInput('ycol', 'Y Variable', "", selected = "")
),
mainPanel(
plotOutput('MyPlot')
)
)
)
)
)
)
server <- shinyServer(function(input, output, session) {
data <- reactive({
req(input$file1)
inFile <- input$file1
df <- read.csv(inFile$datapath, header = input$header, sep = input$sep,
quote = input$quote)
updateSelectInput(session, inputId = 'xcol', label = 'X Variable',
choices = names(df), selected = names(df))
updateSelectInput(session, inputId = 'ycol', label = 'Y Variable',
choices = names(df), selected = names(df)[2])
return(df)
})
output$contents <- renderTable({
data()
})
output$MyPlot <- renderPlot({
x <- data()[, c(input$xcol, input$ycol)]
pROC::roc(input$xcol,input$ycol)
})
})
shinyApp(ui, server)
I have tried to use different codes available in blogs, however, I did not find anything similar. It is possible to reproduce simple plots, like histograms but when I try to import the package proc for example there are always errors associated in this case: 'response' must have two levels
The input variable that you get in the server lists the column names in xcol and ycol. pROC's roc function expects the data itself, which you need to get from your data like for instance:
pROC::roc(x[[input$xcol]], x[[input$ycol]])
Related
Shinymeta is quite underutilized but extremely powerful. If you search "shinymeta" on Stackoverflow, you'll just get 9 results (not counting this one). The functionality captures the logic in the shiny and exposes it as code which then can be run outside the shiny. which ensures the reproducibility of the app.
So, my question is, how can we implement shinymeta in the basic shiny to capture the logic and expose it as code?
Thanks in advance.
library(shiny)
library(ggplot2)
library(datasets)
library(shinymeta)
ui <- shinyUI(fluidPage(
titlePanel("Plot"),
tabsetPanel(
tabPanel("Upload File",
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
tags$br(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"')
),
mainPanel(
tableOutput('contents')
)
)
),
tabPanel("First Type",
pageWithSidebar(
headerPanel('My First Plot'),
sidebarPanel(
selectInput('xcol', 'X Variable', ""),
selectInput('ycol', 'Y Variable', "", selected = ""),
actionButton("generateCode_1", label = "reproducibility!", icon = icon("code"),width=140)
),
mainPanel(
plotOutput('MyPlot', click = "plot_click",
hover = hoverOpts(id = "plot_hover", delayType = "throttle"),
brush = brushOpts(id = "plot_brush")),
hr(),
tableOutput("plot_brushedpoints"),
hr()
)
)
)
)
)
)
server <- shinyServer(function(input, output, session) {
data <- reactive({
req(input$file1)
inFile <- input$file1
df <- read.csv(inFile$datapath, header = input$header, sep = input$sep,
quote = input$quote)
updateSelectInput(session, inputId = 'xcol', label = 'X Variable',
choices = names(df), selected = names(df))
updateSelectInput(session, inputId = 'ycol', label = 'Y Variable',
choices = names(df), selected = names(df)[2])
return(df)
})
output$contents <- renderTable({
data()
})
output$MyPlot <- renderPlot({
graph <- ggplot(data(), aes(.data[[input$xcol]], .data[[input$ycol]])) +
geom_point(position='jitter')
graph
})
output$plot_brushedpoints <- renderTable({
df<- data()
res <- brushedPoints(df, input$plot_brush,
xvar = input$xcol,
yvar = input$ycol,
panelvar1 = NULL,
panelvar2 = NULL,
allRows = FALSE
)
if (nrow(res) == 0|is.null(res))
return(NULL)
res
})
observeEvent(input$generateCode_1, {
code <- expandChain(
quote({
print("The code should appear here ")
})
)
displayCodeModal(
code = code,
title = "Code for reproducibility"
)
})
})
shinyApp(ui, server)
We can't select any X variable when I upload a files and there is no graphic either can you help please?
I want to create that when you upload a CSV files it can gives you a graphic and analyze it.
I am on R studio with shiny
ui <- fluidPage(
tabPanel("Upload File",
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('.csv')),
,
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
selectInput('xcol', 'X Variable', "", selected = NULL),
selectInput('ycol', 'Y Variable', "", selected = NULL)
),
mainPanel(
tableOutput('contents'),
plotOutput('MyPlot')
)
)
)
)
)
)
server <- function(input, output, session) ` {
output$files <- renderTable(input$upload$datapath)
output$summary<-renderPrint(input$upload$datapath)
myfiles <-read.csv(input$upload$datapath)
observeEvent( myfiles , {
updateSelectInput(
session,
inputId = 'xcol',
label = 'X Variable',
choices = names(myfiles),
selected = names(myfiles),
)
updateSelectInput(
session,
inputId = 'ycol',
label = 'Y Variable',
choices = names(myfiles),
selected = names(myfiles),
)
} )
obersveEvent( output$plot<-renderPlot({req(r$myfiles)
p<-ggplot(data=myfiles, aes(sym(input$xcol), sym(input$ycol , print(p)))) +geom_histogram()+theme_gray()
})))
shinyApp(ui , server)
Your code is riddled with problems. I'll try to list everything I found, but it's possible I missed one or two.
You define fileInput('file1',...) but use input$upload$datapath.
Ditto, plotOutput("MyPlot") and output$plot.
There are extra commas and parens throughout the code
There is a print(p) in the middle of the aeshetics within sym.
You call read.csv(..) outside of a reactive but your app needs it to be reactive, so ... make it reactive, and then replace myfiles with myfiles().
The updateSelectInput calls provide a full vector to selected=, it should be a length 1.
geom_histogram can only have an x or a y aesthetic, not both.
(Not a bug, but you define both output$files and output$summary but never use them.)
Here's a work shiny app that uses geom_point.
library(shiny)
library(ggplot2)
ui <- fluidPage(
tabPanel(
"Upload File",
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('.csv')),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
choices = c(Comma=',', Semicolon=';', Tab='\t'),
selected = ','),
selectInput('xcol', 'X Variable', "", selected = NULL),
selectInput('ycol', 'Y Variable', "", selected = NULL)
),
mainPanel(
tableOutput('contents'),
plotOutput('MyPlot')
)
)
)
)
server <- function(input, output, session) {
# output$files <- renderTable(input$file1$datapath)
# output$summary<-renderPrint(input$file1$datapath)
myfiles <- reactive({
req(input$file1$datapath, file.exists(input$file1$datapath))
read.csv(input$file1$datapath)
})
observeEvent(myfiles(), {
req(myfiles())
nms <- colnames(myfiles())
updateSelectInput(
session,
inputId = 'xcol',
label = 'X Variable',
choices = nms, selected = nms[1]
)
updateSelectInput(
session,
inputId = 'ycol',
label = 'Y Variable',
choices = nms, selected = nms[1]
)
})
output$MyPlot <- renderPlot({
req(myfiles(), input$xcol, input$ycol)
ggplot(data = myfiles(), mapping = aes_string(input$xcol, input$ycol)) +
geom_point() +
theme_gray()
})
}
shinyApp(ui , server)
I want to upload in csv/txt file with id, time, concentration and plot (time(x-axis) vs conc(y-axis). My app starts and crashes. When I am trying to bring updateselctinput function outside reactive the shiny app does not run.
Can someone tell me why this is happening ?
I pasted my code below:
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title="Dashboard"),
dashboardSidebar(
sidebarMenu(
menuItem("Input Data", tabName = "dashboard", icon = icon("dashboard")))),
dashboardBody(
tabItems(
tabItem(tabName = "dashboard",
tabPanel("Input Route",
# First tab content
fileInput("df", "Choose text/csv File",
multiple = FALSE,
accept = c("text/csv"))),
tags$br(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"'),
tabPanel("First Type",
# "Empty inputs" - they will be updated after the data is uploaded
selectInput('xcol', 'X Variable', ""),
selectInput('ycol', 'Y Variable', "", selected = ""),
selectInput('ide','Group',"",selected="")
))),
fluidRow(
box(plotOutput("Plot1"),height = 250)
)
))
server <- function(input, output,session) {
data <- reactive({
inFile <- input$df
df <- read.csv(inFile$datapath, header = input$header)
return(df)
})
observe({
df1 = data()
updateSelectInput(session,inputId = 'xcol', label = 'X Variable',
choices = names(df1), selected =names(df1)[2])
updateSelectInput(session,inputId = 'ycol', label = 'Y Variable',
choices = names(df1), selected = names(df1)[2])})
### Plot
output$Plot1<-renderPlot({plot(Plot1<-data()%>%ggplot()+
geom_line(aes(x=input$xcol,y=input$ycol))+
theme_bw())})
}
shinyApp(ui, server)
How about this?
library(shiny)
library(datasets)
ui <- shinyUI(fluidPage(
titlePanel("Column Plot"),
tabsetPanel(
tabPanel("Upload File",
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
# added interface for uploading data from
# http://shiny.rstudio.com/gallery/file-upload.html
tags$br(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"')
),
mainPanel(
tableOutput('contents')
)
)
),
tabPanel("First Type",
pageWithSidebar(
headerPanel('My First Plot'),
sidebarPanel(
# "Empty inputs" - they will be updated after the data is uploaded
selectInput('xcol', 'X Variable', ""),
selectInput('ycol', 'Y Variable', "", selected = "")
),
mainPanel(
plotOutput('MyPlot')
)
)
)
)
)
)
server <- shinyServer(function(input, output, session) {
# added "session" because updateSelectInput requires it
data <- reactive({
req(input$file1) ## ?req # require that the input is available
inFile <- input$file1
# tested with a following dataset: write.csv(mtcars, "mtcars.csv")
# and write.csv(iris, "iris.csv")
df <- read.csv(inFile$datapath, header = input$header, sep = input$sep,
quote = input$quote)
# Update inputs (you could create an observer with both updateSel...)
# You can also constraint your choices. If you wanted select only numeric
# variables you could set "choices = sapply(df, is.numeric)"
# It depends on what do you want to do later on.
updateSelectInput(session, inputId = 'xcol', label = 'X Variable',
choices = names(df), selected = names(df))
updateSelectInput(session, inputId = 'ycol', label = 'Y Variable',
choices = names(df), selected = names(df)[2])
return(df)
})
output$contents <- renderTable({
data()
})
output$MyPlot <- renderPlot({
# for a histogram: remove the second variable (it has to be numeric as well):
# x <- data()[, c(input$xcol, input$ycol)]
# bins <- nrow(data())
# hist(x, breaks = bins, col = 'darkgray', border = 'white')
# Correct way:
# x <- data()[, input$xcol]
# bins <- nrow(data())
# hist(x, breaks = bins, col = 'darkgray', border = 'white')
# I Since you have two inputs I decided to make a scatterplot
x <- data()[, c(input$xcol, input$ycol)]
plot(x)
})
})
shinyApp(ui, server)
Check out the link below for several additional ideas of how to deal with this.
https://shiny.rstudio.com/gallery/
app.R
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title="Dashboard"),
dashboardSidebar(
sidebarMenu(
menuItem("Input Data", tabName = "dashboard", icon = icon("dashboard")))),
dashboardBody(
tabItems(
tabItem(tabName = "dashboard",
tabPanel("Input Route",
# First tab content
fileInput("df", "Choose text/csv File",
multiple = FALSE,
accept = c("text/csv"))),
tags$br(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"'),
tabPanel("First Type",
selectInput('xcol', 'X Variable', ""),
selectInput('ycol', 'Y Variable', "", selected = ""),
selectInput('ide','Group',"",selected="")
))),
# Boxes need to be put in a row (or column)
fluidRow(
box(plotOutput("Plot1"),height = 250)
)
))
server <- function(input, output,session) {
data <- reactive({
shiny::req(input$df)
inFile <- (input$df)
df <- read.csv(inFile$datapath, header = input$header)
return(df)
})
observe({
df1 = data()
updateSelectInput(session,inputId = 'xcol', label = 'X Variable',
choices = names(df1), selected =names(df1)[2])
updateSelectInput(session,inputId = 'ycol', label = 'Y Variable',
choices = names(df1), selected = names(df1)[2])})
output$Plot1<-renderPlot({plot(Plot1<-data()%>%ggplot()+
geom_line(aes_string(x=input$xcol,y=input$ycol))+
theme_bw())})
}
shinyApp(ui, server)
My Shiny Application's purpose is to upload a .csv file and plot a ggplot graph with its data.
When I upload a .csv file on my Shiny Application, the default variable is "y" for both input variables. However, when I change "y" to "x" on the "X Variable" input, the App works fine.
I just have to set "x" for "X Variable" input and "y" for "Y Variable" input as default when I upload the .csv file.
Here follows the app.R code with my comments and Error Message I get when I upload the file.
library(shiny)
library(datasets)
library(ggplot2)
ui <- shinyUI(fluidPage(
titlePanel("Column Plot"),
tabsetPanel(
tabPanel("Upload File",
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
tags$br(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
selectInput('xcol', 'X Variable', "", selected = NULL),
selectInput('ycol', 'Y Variable', "", selected = NULL)
),
mainPanel(
tableOutput('contents'),
plotOutput('MyPlot')
)
)
)
)
)
)
server <- shinyServer(function(input, output, session) {
data <- reactive({
req(input$file1)
inFile <- input$file1
df <- read.csv(inFile$datapath, header = input$header, sep = input$sep)
## Update inputs
## I've already tried to change the selected = names(df) to selected = NULL on this part of the server code, but it didn't work.
updateSelectInput(session, inputId = 'xcol', label = 'X Variable',
choices = names(df), selected = names(df))
updateSelectInput(session, inputId = 'ycol', label = 'Y Variable',
choices = names(df), selected = names(df)[2])
return(df)
})
output$contents <- renderTable({
data()
})
output$MyPlot <- renderPlot({
xy <- data()[, c(input$xcol, input$ycol)]
ggplot(data = xy, aes(x, y)) +
geom_line() +
geom_point()
})
})
shinyApp(ui, server)
The error message I get is:
"Error: object 'x' not found".
and welcome to SO 🤘
Your issue here is that you update the selectInput() at the wrong time: the update is done once the server has finished computing, so here once the data() is done running.
So to be clear, you update your input after trying to select from it.
Other thing is that you need to sym() & !! the input$ to make it work with ggplot() (see : https://github.com/ColinFay/tidytuesday201942/blob/master/R/mod_dataviz.R#L184 for example)
Here is a working version:
library(shiny)
library(datasets)
library(ggplot2)
library(rlang)
ui <- shinyUI(fluidPage(
titlePanel("Column Plot"),
tabsetPanel(
tabPanel("Upload File",
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
tags$br(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
selectInput('xcol', 'X Variable', "", selected = NULL),
selectInput('ycol', 'Y Variable', "", selected = NULL)
),
mainPanel(
tableOutput('contents'),
plotOutput('MyPlot')
)
)
)
)
)
)
server <- shinyServer(function(input, output, session) {
r <- reactiveValues(
df = NULL
)
observe({
req(input$file1$datapath)
# req(input$xcol)
# req(input$ycol)
r$df <- read.csv(
input$file1$datapath,
header = input$header,
sep = input$sep
)
})
observeEvent( r$df , {
updateSelectInput(
session,
inputId = 'xcol',
label = 'X Variable',
choices = names(r$df),
selected = names(r$df)[1]
)
updateSelectInput(
session,
inputId = 'ycol',
label = 'Y Variable',
choices = names(r$df),
selected = names(r$df)[2]
)
}, ignoreInit = TRUE)
output$contents <- renderTable({
req(r$df)
head(r$df)
})
output$MyPlot <- renderPlot({
req(r$df)
req(input$xcol)
req(input$ycol)
ggplot(
data = r$df,
aes(!!sym(input$xcol), !!sym(input$ycol))
) +
geom_line() +
geom_point()
})
})
shinyApp(ui, server)
I want to create a shiny app to draw scatterplots by selecting the variables in the uploaded data set to shiny app. I want to create plots using ggplot and plotly. The code I tried is as follow. But my app does not give the plot.
library(shiny)
library(datasets)
library(plotly)
ui <- shinyUI(fluidPage(
titlePanel("Column Plot"),
tabsetPanel(
tabPanel("Upload File",
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
tags$br(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"')
),
mainPanel(
tableOutput('contents')
)
)
),
tabPanel("First Type",
pageWithSidebar(
headerPanel('My First Plot'),
sidebarPanel(
# "Empty inputs" - they will be updated after the data is uploaded
selectInput('xcol', 'X Variable', ""),
selectInput('ycol', 'Y Variable', "", selected = "")
),
mainPanel(
plotOutput('MyPlot')
)
)
)
)
)
)
server <- function(input, output, session) {
data <- reactive({
req(input$file1)
inFile <- input$file1
df <- read.csv(inFile$datapath, header = input$header, sep = input$sep,
quote = input$quote)
updateSelectInput(session, inputId = 'xcol', label = 'X Variable',
choices = names(df), selected = names(df))
updateSelectInput(session, inputId = 'ycol', label = 'Y Variable',
choices = names(df), selected = names(df)[2])
return(df)
})
output$contents <- renderTable({
data()
})
output$trendPlot <- renderPlotly({
# build graph with ggplot syntax
p <- ggplot(data(), aes_string(x = input$xcol, y = input$ycol)) + geom_point()
ggplotly(p)
})
}
shinyApp(ui, server)
In the above code, the following section doesn't seem to work.
output$trendPlot <- renderPlotly({
# build graph with ggplot syntax
p <- ggplot(data(), aes_string(x = input$xcol, y = input$ycol)) + geom_point()
ggplotly(p)
})
Actually the problem is not in output$trendPlot but in mainPanel(...)
1 : Look closely, in mainPanel, you're calling plotOutput('MyPlot') but output$MyPlot doesn't exist, only plot that exists is output$trendPlot.
2 : Note output$trendPlot <- renderPlotly({...}), return type of trendPlot is renderPlotly but plotOutput is being called at main.
So, fix is
mainPanel(
plotlyOutput('trendPlot')
)
After fixing this, output is as follows :