How to create a multi variable date range plots with plotly - r

I have the following dataset
Date, IMEI
22-7-2017, I
23-7-2017, I
24-7-2017, I
25-7-2017, I
26-7-2017, C
27-7-2017, C
28-7-2017, C
29-7-2017, C
30-7-2017, C
31-7-2017, A
01-8-2017, A
02-8-2017, A
03-8-2017, A
04-8-2017, I
05-8-2017, C
06-8-2017, A
07-8-2017, A
07-8-2017, A
08-8-2017, I
09-8-2017, I
09-8-2017, A
09-8-2017, C
and i want to create an interactive plot to visualize it using plotly to allow the user set the date range manually in "R Shiny" using a dateRangeInput function in r shiny, I've tried the following but still getting wrong plot
ui = fluidpage(
sidebarPanel(
dateRangeInput(inputId="myDateRange", label="", start = NULL, end = NULL, min = NULL, max = NULL),
))
mainPanel(
plotlyOutput("")
)
server = function(input, output, session) {
output$age <- renderPlotly({
plot_ly(a1, x= a1$Date, y = a1$IMEI)
})

Here is a reproducible example.
First, make sure your Date column in your data is a Date object.
Your ui needed minor edits, including capital "P" in fluidPage and adjustment of parentheses. Your plotlyOutput needed an "InputId" - looks like you want to use age based on server.
Next, in server you can subset your data based on the dateRangeInput. There are 2 values input$myDateRange[1] and input$myDateRange[2] - corresponding to the lower and higher limits of the input chosen. You can subset your data and include rows of data where Date is between those values.
Otherwise, I selected some example settings for plot_ly to use.
df$Date <- as.Date(df$Date, format = "%d-%m-%Y")
library(shiny)
library(plotly)
ui = fluidPage(
sidebarPanel(
dateRangeInput(inputId="myDateRange", label="", start = NULL, end = NULL, min = NULL, max = NULL),
),
mainPanel(
plotlyOutput("age")
)
)
server = function(input, output, session) {
output$age <- renderPlotly({
plot_ly(
data = subset(df, Date > input$myDateRange[1] & Date < input$myDateRange[2]),
x = ~Date,
y = ~IMEI,
type = "scatter",
mode = "markers")
})
}
shinyApp(ui, server)

Related

I've added a date range slider to my plotly scatterplot in shiny, but how do I get the data to change according to the widget?

I am trying to have the selectinput widget "Years - Slide" change the data used by the graph to the specific date range shown. I was able to connect the axis options in the ui code to the server code since the graph changes, but I do not know how to do the same to the date range widget.
I am trying to use a selectInput widget instead of a date input widget since I only have the year to work with.
Would anyone know how to resolve this?
I was expecting to see the graph according to the changes in the widget, but that is not working.
functional code without selectinput in the server code
library(gapminder)
gm <- gapminder
library(shiny)
library(plotly)
library(tibble)
library(tidyverse)
library(tidyr)
library(readr)
library(dplyr)
library(ggplot2)
# set working directory
setwd("~/BDSWD")
# Define UI ----
ui <- fluidPage(
column(3,offset = 4, titlePanel("Explore Gapminder Data with Shiny")),
headerPanel('Graphs'),
mainPanel(
plotlyOutput('plot')
),
sidebarPanel(
#variable selection for x-axis
selectInput(inputId ='xvrbl', #The input slot that will be used to access the value.
label = 'X-Axis Variable', #Display label for the control, or NULL for no label.
choices = colnames(gm), #List of values to select from
selected = 'lifeExp'
),
#variable selection for y-axis
selectInput(inputId ='yvrbl', #The input slot that will be used to access the value.
label = 'Y-Axis Variable', #Display label for the control, or NULL for no label.
choices = colnames(gm), #List of values to select from
selected = 'gdpPercap'
),
#date range - slider
sliderInput(inputId = "time",
label = "Years - Slide",
min = min(gm$year),
max = max(gm$year),
step = 5,
value = c(min(gm$year),max(gm$year))),
)
)
server <- function(input, output) {
x <- reactive({
pull(gm[,input$xvrbl])
})
y <- reactive({
pull(gm[,input$yvrbl]) #pull used to turn tibble into vctr bc plotly only takes vctrs
})
output$plot <- renderPlotly(
plot1 <- plot_ly(
x = x(),
y = y(),
type = 'scatter',
mode = 'markers',
color = gm$continent,
data <- subset(gm,
continent %in% input$continents &
year >= input$years[1] & year <= input$years[2])
)
)
}
# Run the app
shinyApp(ui = ui, server = server)
code with my attempt to connect selectInput to the server code (not working)
Unfortunately you code was not working. As first step I added a reactive to create the filtered dataset based on the user input. Second step was to add the selectInput to select the year to be plotted.
library(gapminder)
library(shiny)
library(plotly)
library(tidyverse)
gm <- gapminder
# Define UI ----
ui <- fluidPage(
column(3, offset = 4, titlePanel("Explore Gapminder Data with Shiny")),
headerPanel("Graphs"),
mainPanel(
plotlyOutput("plot")
),
sidebarPanel(
# variable selection for x-axis
selectInput(
inputId = "xvrbl", # The input slot that will be used to access the value.
label = "X-Axis Variable", # Display label for the control, or NULL for no label.
choices = colnames(gm), # List of values to select from
selected = "lifeExp"
),
# variable selection for y-axis
selectInput(
inputId = "yvrbl", # The input slot that will be used to access the value.
label = "Y-Axis Variable", # Display label for the control, or NULL for no label.
choices = colnames(gm), # List of values to select from
selected = "gdpPercap"
),
# date range - slider
selectInput(
inputId = "time",
label = "Years - Slide",
choices = unique(gm$year),
selected = max(gm$year)
)
)
)
server <- function(input, output) {
x <- reactive({
dat()[[input$xvrbl]]
})
y <- reactive({
dat()[[input$yvrbl]]
})
dat <- reactive({
subset(gm, year %in% input$time)
})
output$plot <- renderPlotly({
plot_ly(
x = x(),
y = y(),
type = "scatter",
mode = "markers",
color = dat()$continent
)
})
}
# Run the app
shinyApp(ui = ui, server = server)
#>
#> Listening on http://127.0.0.1:5182

Referencing a selected input into a dataset?

I am currently having issues with my R.Shiny app which I have designed. The UI has a drop down menu which selects a variable "returnvar", one of the columns in my dataframe source_file. However, upon running the code below I receive an error message stating:
Warning: Unknown or uninitialised column: 'returnvar'.
Warning: Error in : geom_line requires the following missing aesthetics: y
Does anyone know how I can reference an input into my source file? (Something to fix the error from the line source_file_filtered$returnvar) Would greatly appreciate all the help I can get for this, thanks!
App.R
# Defining UI
ui <- fluidPage(theme = shinytheme("darkly"),
navbarPage(
"App", #Title of app
tabPanel("Weekly Cumulative Returns",
sidebarPanel(
tags$h3("Input:"),
dateRangeInput("daterange", "Date range",
start = "2016-01-01",
end = "2021-04-02",
min = "2016-01-01",
max = "2021-04-02",
format = "yyyy/mm/dd",
separator = "to"),
selectInput("returnvar", "Index",
choices= names(source_file[2:(length(source_file)-1)])),
), #sidebarpanel
mainPanel(
# Output: Correlation Plot ----
plotOutput(outputId = "plot2"),
), #mainPanel
) #tabpanel
) #navbarPage
) #fluidPage
# Defining Server
server <- function(input, output) {
#plot for Weekly Cumulative Returns tab
output$plot2 <- renderPlot({
returncolumn(returnvar = input$returnvar,
daterange = input$daterange)
})
}
# Create Shiny Object
shinyApp(ui = ui, server = server)
Global.R
#choose source file to work with
file_name = file.choose()
source_file = read_csv(file_name)
source_file$Date = as.Date(source_file$Date)
#defining returncolumn as a function to return of selected variable over the selected date range in shiny
returncolumn = function(returnvar, daterange)
{
source_file_filtered <- source_file %>%
filter(Date >= daterange[1] & Date <= daterange[2])
g = ggplot(data = source_file_filtered, mapping = aes(x=Date, y=source_file_filtered$returnvar)) + geom_line(color="blue")
print(g)
}
Without the data its hard to test, but changing source_file_filtered$returnvar to source_file_filtered[[returnvar]] should make it work.
returncolumn = function(returnvar, daterange)
{
source_file_filtered <- source_file %>%
filter(Date >= daterange[1] & Date <= daterange[2])
g = ggplot(data = source_file_filtered,
mapping = aes(x = Date,
y = source_file_filtered[[returnvar]])) +
geom_line(color="blue")
print(g)
}

Shiny: Plotting a graph whose name contains an interactive input value

In ShinyApp, I want to plot a graph whose name has an interactive input value. So in the ui.R side, the user chooses an input value from 0, 1 or 2. And in the server.R side, I want the App to plot a graph whose name is either pl0, pl1 or pl2. That is to say, if the user chooses 0 as an input value, the App plots a graph pl0, so does the same for pl1 for input 1, and for pl2 and input 2. I am using plotly library for plotting graphs.
I have tried print(), plot(), return(), but neither of them worked.
Any solution or advice would be appreciated. Thank you very much!
Here is my ui.R
library(shiny)
shinyUI(fluidPage(
# Application title
titlePanel("Star Cluster Simulations"),
# Sidebar with a slider input for time
sidebarLayout(
sidebarPanel(
sliderInput(inputId = "time",
label = "Select time to display a snapshot",
min = 0,
max = 2,
value = 0)
),
# Show a plot of the generated distribution
mainPanel(
plotlyOutput("distPlot")
)
)
))
And here is my server.R
library(shiny)
library(plotly)
# load data
for(i in 0:2) {
infile <- paste0("Data/c_0", i, "00.csv")
a <- read.csv(infile)
b <- assign(paste0("c_0", i, "00"), a)
names(a) <- paste0("c_0", i, "00")
pl <- plot_ly(b, x = ~x, y = ~y, z = ~z, color = ~id) %>%
add_markers() %>%
layout(scene = list(xaxis = list(title = 'x'),
yaxis = list(title = 'y'),
zaxis = list(title = 'z')))
assign(paste0("pl", i), pl)
}
# shinyServer
shinyServer(function(input, output) {
output$distPlot <- renderPlotly({
# this doesn't work
print(paste0("pl", input$time))
})
})
I can't test this since your question isn't reproducible (i.e. doesn't include data), but one way to switch between text values (i.e. the values returned from Shiny inputs) and R objects is by making a reactive expression that uses the switch function. You can call the reactive expression (in the case below, plot.data()) inside renderPlotly (or any other render function) to switch between datasets.
shinyServer(function(input, output) {
plot.data <- reactive({
switch(paste0("pl", input$time),
"pl0" = pl0,
"pl1" = pl1,
"pl2" = pl2)
})
output$distPlot <- renderPlotly({
plot.data()
})
})

Subsetting in r shiny

I've been working on a visualization project in shiny. I'm trying to filter a data set by given input - number of state and range of the slider. Unfortunately, r 'omits' the the code part and outputs the entire data set. I also get warnings: 'data' is not a graphical parameter.
library(shiny)
library(Ecdat)
u <- shinyUI(pageWithSidebar(
headerPanel("Social benefits"),
sidebarPanel(
selectInput("variable", "Variable:",
list("Unemployment",
"Max benefit"
)),
#Specification of state
textInput("state", "State:", value = "93"),
# Specification of range within an interval
sliderInput("range", "Range:",
min = 1, max = 100, value = c(20,100))
),
mainPanel(
plotOutput("mpgPlot")
)
))
s <- shinyServer(function(input, output)
{
#filter by state -ERROR
p <- reactive({ Benefits[Benefits$state == input$state,]})
#filter by slider range - ERROR
dataX <- reactive({ p()[input$range[1]:input$range[2],,drop = FALSE] })
variable <- reactive({
switch(input$variable,
"Unemployment" = stateur,
"Max benefit" = statemb
)
})
caption <- reactive({
paste(input$variable)
})
output$mpgPlot <- renderPlot({
plot(variable(), data = dataX(), type = "l",ylab = caption())
})
})
shinyApp(u,s)
All that was actually needed was to specify the data set name before the variable, since the data set from the environment was overshadowing the filtered one.
output$urPlot <- renderPlot({
plot(dataX()$stateur, data = dataX(), type = "l",ylab = "Unemployment")
})
output$mbPlot <- renderPlot({
plot(dataX()$statemb, data = dataX(), type = "l",ylab = "Max benefit")
})

How can I use daterangenput for time series plot?

I have data to be plotted as series which is uploded by user. However, the data is for one year and I would like to display 2 months for instance, january and february when the user needs to analyze the pattern of these months. That's why i thought that dateRangeInput can be useful but i dont know how can i bind with plot?
for data: http://www.filedropper.com/quo
EDITED: I used the reactive argument in order get the inputs. However, it shows another error: Error in charToDate(x) :
character string is not in a standard unambiguous format.
library(shiny)
shinyUI(fluidPage(
titlePanel("Time Series Study"),
sidebarLayout(
sidebarPanel(
fileInput('file2', 'Choose Quotation File:', accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv'), multiple = FALSE),
dateRangeInput("range",
"Date Range:",
start = "start",
end = "end",
min = "2012.01.01",
max = "2012.01.31")
),
mainPanel(
plotOutput("distPlot") ) ) ))
#server.r
library(shiny)
library(ggplot2)
shinyServer(function(input, output) {
dataInput <- reactive({
`uploadedsamplefile` <- read.csv(input$file2$datapath, sep=";",check.names = FALSE)
uploadedsamplefile1 <- uploadedsamplefile
xx<-cbind(`uploadedsamplefile1`[1:4])
xx$`Datee` <- as.Date( xx$`Datee`, '%d.%m.%Y')
xx$`Datee` <- subset( xx$`Datee`, as.Date("input$start") <= xx$`Datee` && xx$`Datee` <= as.Date("input$end"))
})
output$distPlot <- renderPlot({
y <- ggplot(xx, aes(x=`Datee`)) + geom_line(aes(y=(`A`), colour = "A")) + geom_line(size=1,aes(y=(`B`), colour = "B")) +
geom_line(size=1,aes(y=(`C`), colour = "C"))
y }) })
To access the start and end dates in your example use input$range[1] for the start date and input$range[2] to access the end date.

Resources