I am trying to subset a data set using a few input parameters and then plot the output. I am able to plot various stats over time for various teams, but I am unable to figure out how to subset my data for an input date range. Attached is my server and ui.
Server:
library(shiny)
season = read.csv("2016_Season.csv")
season$date = as.POSIXct(season$date)
function(input, output) {
adjust <- function() {
data = season
#data = data[data$date >= input$dates[1],]
#data = data[data$date <= input$dates[2],]
if (input$Team != "All"){
data <- data[data$Team == input$Team,]
}
data = data[,c('date',input$Stat)]
}
output$distPlot <- renderPlot({
plot(adjust())
})
}
UI:
library(shiny)
season = read.csv("2016_Season.csv")
season$date = as.POSIXct(season$date)
shinyUI(fluidPage(
titlePanel("Time Plot"),
sidebarPanel(
fluidRow(
div(class="span4",
selectInput('Team',
'Team:',
c('All',unique(as.character(season$Team)))))
),
fluidRow(
div(class="span4",
selectInput("Stat",
"Stat:",
c('PTS','TRB','AST')))
),
dateRangeInput("dates",
"Date range",
start = min(season$date),
end = max(season$date))
),
mainPanel(
plotOutput("distPlot")
)
))
The code works fine when the these two lines are commented out in the server, though obviously the date filters dont work:
#data = data[data$date >= input$dates[1],]
#data = data[data$date <= input$dates[2],]
but I remove the comments i get the error 'need finite 'xlim' values' and I am not sure how to fix it.
Related
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)
I am trying to run an interactive rshiny plot. I have this output:
I want to be able to subset and plot by country, by scenario, by variable, by year (4 selections). I also want to be able to add value points by year and not have the whole plot by year done immediately.
I am only able to subset by country. My scenario and variable dropdowns are not reactive. And it plots all variables with all scenarios although I want one variable plot by one scenario and one country
How can I make my graph interactive?
library(reshape2)
library(lattice)
library(plyr)
library(shiny)
library(dplyr)
library(abind)
library(ggplot2)
ui <- fluidPage(
titlePanel("Comparing Trend and PP policies by MDGs and funding"),
sidebarLayout(
sidebarPanel(
radioButtons("radio", label = h3("Country"),choices=unique(dmiubf$country), selected = ""),
selectInput("Senario","Show senario:", choices = unique(dmiubf$scn)),
selectInput("var","Show senario:", choices = unique(dmiubf$var)),
selectInput("year","Show vertical line in year(s):", choices = unique(dmiubf$year),multiple=TRUE)
),
mainPanel(
plotOutput("chart")
)
)
)
server <- function(input, output) {
cr <- reactive({
a = dmiubf[dmiubf$var==input$var, dmiubf$scn==input$senario]<-dmiubf[dmiubf[,"country"]=="Costa Rica",input$senario]<-"base"
dmiubf
})
output$chart <- renderPlot({
req(input$radio)
if (input$radio==c("Costa Rica")) {
plot0<-ggplot(data=cr()) + geom_point(aes(x=year,y=pcn, fill=scn),
size = 6)
print(plot0)
}
})
}
shinyApp(ui = ui, server = server)
I tried fixing your app, but without knowing how the input data looks like, its a bit hard. So i created a random dummy dataset. Therefore it is not always showing a plot, as no data is left after the filtering process.
But as a starting point I think this should help you:
library(shiny)
library(dplyr)
library(ggplot2)
dmiubf <- data.frame(
country=c(rep("Costa Rica",8), rep("England",8), rep("Austria",8), rep("Latvia",8)),
scn = rep(c("base","high","low","extra"),8),
year = sample(c(1998, 1999, 2000, 2001), 32, replace = T),
var = sample(c(1,2,3,4), 32, replace = T),
pcn = sample(c(10,20,30,40), 32, replace = T)
)
ui <- fluidPage(
titlePanel("Comparing Trend and PP policies by MDGs and funding"),
sidebarLayout(
sidebarPanel(
radioButtons("radio", label = h3("Country"),choices= as.character(unique(dmiubf$country)), selected = ""),
selectInput("Senario","Show senario:", choices = as.character(unique(dmiubf$scn))),
selectInput("var","Show senario:", choices = sort(unique(dmiubf$var))),
selectInput("year","Show vertical line in year(s):", choices = sort(unique(dmiubf$year)), multiple=TRUE)
),
mainPanel(
plotOutput("chart")
)
)
)
server <- function(input, output) {
cr <- reactive({
a <- dmiubf[as.character(dmiubf$country)==input$radio &
dmiubf$var %in% as.numeric(input$var) &
dmiubf$year %in% as.numeric(input$year) &
as.character(dmiubf$scn)==input$Senario
,]
a
})
output$chart <- renderPlot({
validate(
need(nrow(cr())!=0, "No Data to plot")
)
ggplot(data=cr()) + geom_point(aes(x=year, y=pcn, fill=scn), size = 6)
})
}
shinyApp(ui = ui, server = server)
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.
I have a task where i need to build an rShiny app that allows the user to choose which kind of R plotting package is used in-order to display a plot.
Currently the only way i have gotten it to work (semi-decently) is using package specific functions for each package on the server side and using a series of conditional panels on the UI side.
However the problem is that when the user enters the page for the first time then all plots are initialized. Second problem is when the user changes some plot input values and after that chooses another package then the old plot will be displayed until a new plot is created.
Questions:
Is this the only available approach?
I feel that there must be a way to use reactive functions for the package selection?
I feel that it should be possible to use a single rShiny's htmlOutput (or something similar) in the ui and therefore not needing the switchPanel?
I have created a small app to demonstrate my current implementation and both problems:
server.R
library(shiny)
#library(devtools)
#install_github("ramnathv/rCharts")
library(rCharts)
shinyServer(function(input, output) {
names(iris) = gsub("\\.", "", names(iris))
#Render the Generic plot
output$GenericPlot <- renderPlot({
data = iris[0:input$variable,]
plot(data$SepalLength ~ data$SepalWidth)
})
#Render the Polychart plot
output$PolychartPlot <- renderChart({
plotData <- rPlot(SepalLength ~ SepalWidth, data = iris[0:input$variable,], color = 'Species', type = 'point')
plotData$addParams(dom = 'PolychartPlot')
return(plotData)
})
#Render the NDV3 plot
output$NDV3Plot <- renderChart({
plotData <- nPlot(SepalLength ~ SepalWidth, data = iris[0:input$variable,], group = 'Species', type = 'scatterChart')
plotData$addParams(dom = 'NDV3Plot')
return(plotData)
})
})
ui.R
library(shiny)
library(rCharts)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("lib", label = "Library:",
choices = list("Generic", "rCharts Polychart", "rCharts NDV3"),
selected = "Generic"
),
numericInput("variable", "Observations:",
min = 5,
max = 150,
value = 10
)
),
mainPanel(
conditionalPanel(
condition = "input.lib == 'Generic'",
h3("Generic plot"),
plotOutput("GenericPlot")
),
conditionalPanel(
condition = "input.lib == 'rCharts Polychart'",
h3("rCharts Polychart plot"),
showOutput("PolychartPlot", "polycharts")
),
conditionalPanel(
condition = "input.lib == 'rCharts NDV3'",
h3("rCharts NDV3 plot"),
showOutput("NDV3Plot", "nvd3")
)
)
)
))
The final version will use a different dataset and more charting packages. The provided code is more of a toy example, with most of the stuff stripped out.
Make a single part in the output part of the app that includes some logic based on the input. For example,
library(shiny)
library(ggplot2)
data(cars)
server <- function(input, output) {output$plot<- renderPlot({
if (input$lib == "base") {
p <- plot(cars$speed, cars$dist)
} else if (input$lib == "ggplot") {
p <- ggplot(cars, aes(x = speed, y = dist)) + geom_point()
}
p
})
}
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("lib", "Library: ", choices = list("base", "ggplot"),
selected = "base")
),
mainPanel(plotOutput("plot"))
)
)
shinyApp(ui = ui, server = server)
This provides one plot and as soon as I change the lib option it regenerates.
Found a solution to my problem. The solution is basically to use uiOutput() in the ui.R and move the plotOutput(), showOutput() methods to the server.R.
The solution based on iacobus code:
ui.R
library(shiny)
library(rCharts)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("lib", "Library: ", choices = list("base", "ggplot", "Polychart"),
selected = "base")
),
mainPanel(uiOutput("plot"))
)
))
server.R
library(shiny)
library(ggplot2)
library(rCharts)
data(cars)
server <- function(input, output) {
output$plot<- renderUI({
if (input$lib == "base") {
plotOutput("base")
} else if (input$lib == "ggplot") {
plotOutput("ggplot")
} else if (input$lib == "Polychart") {
showOutput("polychart", "polycharts")
}
})
output$base <- renderPlot({
plot(cars$speed, cars$dist)
})
output$ggplot <- renderPlot({
ggplot(cars, aes(x = speed, y = dist)) + geom_point()
})
output$polychart <- renderChart({
p <- rPlot(speed ~ dist, data = cars, type = "point")
p$addParams(dom = 'plot')
p
})
}
The difficulty arose for me, because i assumed that plotOutput(), showOutput() etc methods can only be used in the ui.R. This however is not the case.
EDIT:
It turned out that this was not enough for pollyCharts to work properly along with other rCharts packages.
instead i am using renderUI and rCharts $show to display the chart inline. The following link was helpful for me: https://github.com/ramnathv/rCharts/issues/373. In the ui i'm using htmlOutput
I am using shiny to plot different time series of precipitation and temperature.
ui.R
shinyUI(fluidPage(
# Application title
titlePanel("Parametres"),
plotOutput(outputId = "main_plot", height="500px"),
hr(),
fluidRow(
column(4,
selectInput(inputId = "Cellule",label = "Cellule:",choices = c(17,1404,2478,2792,3842,6103,7714,8442,8642),selected = 7714),
selectInput(inputId = "Variable",label = "Variable:",choices = c("Ptot", "TEMP"),selected = "Ptot")
),
)
))
Here is a part of my code for server.R, which doesn't work:
server.R
shinyServer(function(input, output, p. = p) {
output$main_plot <- renderPlot({
....
if(input$Variable =="TEMP")
{
Obs_inter$value <- Obs_inter$value-273.15
Sim25_inter$value <- Sim25_inter$value-273.15
Sim_1_inter$value <- Sim_1_inter$value-273.15
Sim_2_inter$value <- Sim_2_inter$value-273.15
ymin <- min(Obs_inter$value, Sim25_inter$value, Sim_1_inter$value, Sim_2_inter$value)
ytitle <- "TEMP (°C)"
} else {
if(input$Variable=="Ptot")
{
ymin <- 0
ytitle <- "Ptot (mm)"
}
}
p <- ggplot()
....
})
})
With Obs, Sim25, Sim_1 and Sim_2 my time series.
When I run my code, this is the error I get:
"Cannot find ymin"
So the loop with the if statement doesn't work. I tried to select ymin=0 before (no if statement) and I have what I want. What I do not understand is that I have another if statement before (not with input$Variable but another input) and it works.
I tried to print input$Variable to see what it returns but I don't know how to do that..
Thanks for the help!