Shiny and R combine three graphs into 1 - r

I have developed a basic introductory shiny which downloads stock data and runs 3 technical indicators.
This is the code:
library(shiny)
library(quantmod)
library(dygraphs)
library(TTR)
ui <- shinyUI(fluidPage(
titlePanel("Simple Stock Charting App"),
sidebarLayout(
sidebarPanel(
textInput("symb", label = h3("Input a Valid Stock Ticker"), value = "GE")
),
selectInput("var", label = "bals", choices=list("RSI","Price","ADX")),
### uncomment for dygraphs chart
mainPanel(dygraphOutput("plot"),dygraphOutput("plot2"),dygraphOutput("plot3"))
)
))
server <- shinyServer(function(input, output) {
dataInput <- reactive({
prices <- getSymbols(input$symb, auto.assign = FALSE)
})
output$plot <- renderDygraph({renderPlot
dygraph(Ad(dataInput())) %>%dyRangeSelector()
})
output$plot2 <- renderDygraph({renderPlot
dygraph((RSI(Ad(dataInput()), n = 14))) %>%dyRangeSelector()
})
output$plot3 <- renderDygraph({renderPlot
dygraph((ADX(HLC(dataInput()),n = 14))) %>%dyRangeSelector()
})
})
shinyApp(ui,server)
I would like to know if it is possible the user to choose only of the three indicators each time. Currently, all three are shown but I know its possible to have one graph and based on the selection of the RSI, Value and ADX to change the graph.

You can use switch for what you want:
library(shiny)
library(quantmod)
library(dygraphs)
library(TTR)
ui <- shinyUI(fluidPage(
titlePanel("Simple Stock Charting App"),
sidebarLayout(
sidebarPanel(
textInput("symb", label = h3("Input a Valid Stock Ticker"), value = "GE")
),
selectInput("var", label = "bals", choices=list("RSI","Price","ADX"))
),
### uncomment for dygraphs chart
mainPanel(dygraphOutput("plot"))
))
server <- shinyServer(function(input, output) {
dataInput <- reactive({
getSymbols(input$symb, auto.assign = FALSE)
})
output$plot <- renderDygraph({
data <- switch(input$var,"RSI" = RSI(Ad(dataInput()), n = 14),
"Price" = Ad(dataInput()),
"ADX" = ADX(HLC(dataInput()),n = 14))
dygraph(data) %>%dyRangeSelector()
})
})
shinyApp(ui,server)

Related

Make a boxplot interactive using Shiny

I've been trying to develop an interactive boxplot with selective input in Shiny.
current code:
library(shiny)
shinyUI(fluidPage(
titlePanel("Sample 1"),
sidebarLayout(
sidebarPanel(
selectInput("p", "Choose your salaries", choices = c("low"='a',"mid"='b',"high"='c',"riches!"='d'), selected = 4)
),
mainPanel(
plotOutput("boxplot")
)
)
))
library(shiny)
read.csv("Salaries.csv")
Categories <- cut (Salaries$TotalPay, breaks = c(0,36466,73678,104359,567595), labels = c("low","mid","high","riches!"))
shinyServer(function(input, output){
output$boxplot <- renderPlot({
if(input$p=='a'){
i<"1"
}
if(input$p=='b'){
i<-"2"
}
if(input$p=='c'){
i<-"3"
}
if(input$p=='d'){
i<- "riches!"
}
boxplot(TotalPay~Categories[i])
})
})
I can't get the boxplot to react to the selection made in the UI. I suspect it has to do with the levels as when I call:
> Categories["riches!"]
[1] <NA>
Levels: low mid high riches!
'
Do i need to add factors to these? Or am I missing the point entirely?
Thanks in advance!
Have a look how to access the column by name. Example below is with mtcars dataset
library(shiny)
ui <- fluidPage(
selectInput("p","p",choices = names(mtcars)),
plotOutput("myplot"))
server <- function(input, output, session) {
output$myplot <- renderPlot({
boxplot(mtcars[,input$p])
})
}
shinyApp(ui, server)

R zoomChart Shiny

i've been trying to interactively zoom in certain parts of a chartSeries with zoomChart and shiny, but can't find the right solution. I would use dateRangeInput or a slider, but i'm not sure how to connect the zoomChart-option from quantmod with shiny. As you might have already assumed, I'm relatively new to shiny and very thankful for your advices!
edit: Data is in the xts-format.
MyCode:
library(quantmod)
library(shiny)
date_range <- as.POSIXct(index(data))
if (interactive()) {
options(device.ask.default = FALSE)
ui <- fluidPage(
titlePanel("Select Range to zoom-in:"),
sidebarLayout(
sidebarPanel(
dateRangeInput("Range", "Choose Date Range:", min=first(date_range),
max=last(date_range), format = "dd-mm-yyyy")
),
mainPanel(
plotOutput("Plot")
)
)
)
server <- function(input, output) {
output$Plot <- renderPlot({
chartSeries(data, type = c("auto", "candlesticks", "matchsticks", "bars","line"),
theme=chartTheme("white"), name=paste(start(data), end(data),sep = " "))
zoomChart(dateRangeInput)
})
}
shinyApp(ui, server)
}
Actually, you were very close. Note the changes in dateRangeInput(): The start and end argument are used instead of min, max. And then you can use the input on the server-side to use zoom-chart.
library(quantmod)
library(shiny)
getSymbols("YHOO")
data <- YHOO
date_range <- index(data)
if (interactive()) {
options(device.ask.default = FALSE)
ui <- fluidPage(
titlePanel("Select Range to zoom-in:"),
sidebarLayout(
sidebarPanel(
dateRangeInput("Range", "Choose Date Range:", start=first(date_range),
end=last(date_range), format = "yyyy-mm-dd")
),
mainPanel(
plotOutput("Plot")
)
)
)
server <- function(input, output) {
output$Plot <- renderPlot({
chartSeries(data, type = c("auto", "candlesticks", "matchsticks", "bars","line"),
theme=chartTheme("white"), name=paste(start(data), end(data),sep = " "))
zoomChart(paste(input$Range, collapse = "::"))
})
observe({
print(input$Range)
})
}
shinyApp(ui, server)
}
As #drmariod indicated It would be beneficial to have a fully reproducible exmaple, which was easy to get in this case via getSymbols().

Shiny R: how to evaluate data set name to print the dataset

I want to print data set values in R shiny web app. But below code is printing the name of dataset in UI output. How can I print values of dataset?
library(MASS)
library(shinythemes)
library(shiny)
library(ggplot2)
mass.tmp <- data(package = "MASS")[3]
mass.datasets <- as.vector(mass.tmp$results[,3])
ui <- fluidPage(
theme = shinytheme("superhero"),
titlePanel("Linear Regression Modelling"),
sidebarLayout(
sidebarPanel(
selectInput("dsname", "Dataset:",choices = c(mass.datasets))
,
uiOutput("x_axis")
,
tableOutput("tab")
),
mainPanel(
tags$br(),
tags$br()
)
)
)
server <- function(input, output) {
num_ds <- function(ds)
{
nums <- sapply(ds,is.numeric)
num_ds <- ds[,nums]
return(num_ds)
}
ds_ext <- reactive({ num_ds(input$dsname) })
output$tab <- renderTable({ eval(input$dsname) })
# output$x_axis <- renderUI({
# col_opts <- get(ds_ext())
# selectInput("x_axis2", "Independent Variable:", choices = names(col_opts))
# })
}
shinyApp(ui = ui, server = server)
This is full code. I am trying to display data set from MASS package as you see in the code above.

Chart (rCharts) is not shown in the web page (Shiny)

I am trying to embed the interactive chart from rCharts package. To embed the chart I have used the example from here (Shiny app).
The example works well but my prototype works without the chart output (no errors have been reported). My script is as follows:
ui.r:
library(shiny)
require(rCharts)
shinyUI(fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
showOutput("myChart", "polycharts")
)
)
))
server.r:
library(shiny)
require(rCharts)
shinyServer(function(input, output) {
observeEvent(input$bins,{
df2 <<- data.frame(x=c(1:input$bins),y=c(1:input$bins))
})
output$myChart <- renderChart({
print(df2)
p1 <- rPlot(df2$x,df2$y, data = df2, color='green', type = 'point')
p1$addParams(dom = 'myChart')
return(p1)
})
})
I have reviewed your code and here are some pointers:
1) rPlot is taking data as x~y along with color argument
2) It is better if you use the eventReactive and assign it to df2() instead of observe and <<- global assignment operator
rm(list = ls())
library(shiny)
require(rCharts)
server <- function(input, output) {
df2 <- eventReactive(input$bins,{data.frame(x=c(1:input$bins),y=c(1:input$bins))})
output$myChart <- renderChart({
p1 <- rPlot(x~y, data = df2(), color='green', type = 'point', color = 'x')
p1$addParams(dom = 'myChart')
return(p1)
})
}
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(sidebarPanel(sliderInput("bins","Number of bins:", min = 1,max = 50,value = 30)),
# Show a plot of the generated distribution
mainPanel(showOutput("myChart", "polycharts"))
)
)
shinyApp(ui, server)

Modify my rChart based on a reactive input?

I am having trouble with some code that I've written.
Here is a sample of the dataset: https://docs.google.com/spreadsheets/d/1C_P5xxzYr7HOkaZFfFiDhanqDSuSIrd2UkiC-6_G2q0/edit?usp=sharing
Objective:
I have a dataset that contains a column of Purchase_Month, candy and freq of the number of times that type of candy was purchased in that given month.
I have an rPlot which I was to change based on the chosen Candy bar in the SelectInput. And output a line chart based on the number of times that candy was purchased that month.
I have my current code below, but it tells me that candyCount is not found.
## ui.R ##
library(shinydashboard)
library(rCharts)
dashboardPage(
dashboardHeader(title = "Dashboard"),
dashboardSidebar(
width = 150,
sidebarMenu(
menuItem("Dashboard", tabName = "dashboard", icon = icon("bar-chart"))
)
),
dashboardBody(
sidebarPanel(
htmlOutput("candy")
),
mainPanel(
showOutput("plot2", "polycharts")
))
)
##server.R##
library(rCharts)
library(ggplot2)
library(ggvis)
server <- function(input, output, session) {
output$candy <- renderUI({
available2 <- dataset[(dataset$candy == input$candy), "candy"]
selectInput(
inputId = "candy",
label = "Choose a candy: ",
choices = sort(as.character(unique(available2))),
selected = unique(available2[1])
)
})
observeEvent(input$candy, {
candyChoice<- toString(input$customer_issue)
print(candyChoice)
candyCount<- dataset[dataset$candy == candyChoice, ]
})
})
output$plot2 <- renderChart2({
p2 <- rPlot(freq~purchase_month, data = candyCount, type = 'line')
p2$guides(y = list(min = 0, title = ""))
p2$guides(y = list(title = sprintf("%s Claims",input$candy)))
p2$addParams(height = 300, dom = 'chart2')
return(p2)
})
}
Updated Data: Why wouldn't this work?
candyCount<- reactive({
dataset[dataset$candy == input$candy, ]
})
output$plot2 <- renderChart2({
p2 <- rPlot(freq~purchase, data = candyCount(), type = 'line')
p2$guides(y = list(min = 0, title = ""))
p2$guides(y = list(title = ""))
p2$addParams(height = 300, dom = 'chart2')
return(p2)
})
output$candy <- renderUI({
available2 <- dataset[(dataset$candy == input$candy), "candy"]
selectInput(
inputId = "candy",
label = "Choose a candy: ",
choices = sort(as.character(unique(available2))),
selected = unique(available2[1])
)
})
In the above you are trying to subset by an input, which is inside your output. The selectInput needs to be inside UI.R.
A working basic example you may find useful.
library(shiny)
df <- read.csv("/path/to/my.csv")
ui <- shinyUI(pageWithSidebar(
headerPanel('Candy Data'),
sidebarPanel(
selectInput('candy', 'Candy', unique(as.character(df[,2])), selected = "Twix")
),
mainPanel(
plotOutput('plot1')
)
))
server <- shinyServer(function(input, output, session) {
selectedData <- reactive({
df[which(df[,2] == input$candy),3]
})
output$plot1 <- renderPlot({
barplot(selectedData())
})
})
shinyApp(ui, server)
In the above example the ui renders a selectInput which has the ID candy. The value, i.e the candy selected is now assigned to input$candy scope. In server we have a reactive function watching for any input change. When the user selects a new candy this function, df[which(df[,2] == input$candy),3] is saying "subset my data frame, df, by the new input$candy". This is now assigned to the selectedData(). Finally we render then boxplot.
EDIT
server.R
require(rCharts)
options(RCHART_WIDTH = 500)
df <- read.csv("path/to/my.csv")
shinyServer(function(input, output, session) {
selectedData <- reactive({
df[which(df[,2] == input$candy),]
})
output$plot1 <- renderChart({
p <- rPlot(freq~purchase_month, data = selectedData(), type = "line")
p$addParams(dom = 'plot1')
return(p)
})
})
ui.R
require(rCharts)
options(RCHART_LIB = 'polycharts')
shinyUI(pageWithSidebar(
headerPanel('Candy Data'),
sidebarPanel(
selectInput('candy', 'Candy', unique(as.character(df[,2])), selected = "Twix")
),
mainPanel(
showOutput('plot1', 'polycharts')
)
))
save files in directory and then runApp.
At available2 you're filtering the data about a selected candy with dataset$candy == input$candy. But you use the same available2 to determine which are the choices at selectInput. I'm guessing you wanted: available2 <- dataset[, "candy"].

Resources