How do I put a reactive subset of data into renderplot? - r

I am new to Shiny and have been trying to learn in my spare time. I have a dataframe of Fantasy Football statistics that I am trying to plot based on selectinput()'s and sliderbar()'s. I used renderprint() to ensure my inputs and correct when the slider's or selects are changed. I have the sliders and select inputs in a reactive() where I am simply subsetting the data. I am then feeding the reactive function into my ggplot() as the data. When trying to plot these graphs I am getting an "Error: object 'columnName' not found", but for only some columns. Please help me find the source of this issue.
Best, Davis
Here is the code:
######################################################################
#------------------------Load libraries------------------------------#
######################################################################
library(shiny)
library(bslib)
library(shinydashboardPlus)
library(ggplot2)
library(shinyWidgets)
######################################################################
#------------------------Data import and Clean-----------------------#
######################################################################
FantFootDF <- read_excel("~/Desktop/Fantasy/2021 Fantasy Stats.xltx")
FantFootDF <- as.data.frame(FantFootDF)
colnames(FantFootDF) <- paste(FantFootDF[1,])
FantFootDF <- FantFootDF[-1,]
colnames(FantFootDF) <- c("Rk","Player","Team","FantPos","Age",
"G","GS","Cmp","PAtt","PYds","PTD",
"Int","RuAtt","RuYds","RuYA","RuTD",
"Rec","ReYds","ReYA","ReTD","Fmb","FL",
"TTD","2PM","2PP","FantPt","PPR","DKPt",
"FDPt","VBD","PosRank","OvRank")
FantFootDF[!is.na(FantFootDF$FantPos),]
NumColumns <- c("Rk","Age",
"G","GS","Cmp","PAtt","PYds","PTD",
"Int","RuAtt","RuYds","RuYA","RuTD",
"Rec","ReYds","ReYA","ReTD","Fmb","FL",
"TTD","2PM","2PP","FantPt","PPR","DKPt",
"FDPt","VBD","PosRank","OvRank")
FantFootDF[NumColumns] <- lapply(FantFootDF[NumColumns], as.numeric)
FantFootDF[is.na(FantFootDF)] = 0
FinalDF <- FantFootDF
######################################################################
#------------------------User Interface------------------------------#
######################################################################
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Fantasy Football GUI"),
#Sidebar
sidebarLayout(
sidebarPanel(
pickerInput("position",
"Position(s)",
choices = unique(FinalDF$FantPos),
options = list(`actions-box` = TRUE),
multiple = T),
pickerInput("playername",
"Player Name",
choices = unique(FinalDF$Player),
options = list(`actions-box` = TRUE),
multiple = T),
pickerInput("team",
"Team",
choices = unique(FinalDF$Team),
options = list(`actions-box` = TRUE),
multiple = T),
sliderInput("age",
"Age",
min = min(FinalDF$Age),
max = max(FinalDF$Age),
value = c(min(FinalDF$Age), max(FinalDF$Age))),
sliderInput("completions",
"Completions",
min = min(FinalDF$Cmp),
max = max(FinalDF$Cmp),
value = c(min(FinalDF$Cmp), max(FinalDF$Cmp))),
sliderInput("Pattempts",
"Passing Attempts",
min = min(FinalDF$PAtt),
max = max(FinalDF$PAtt),
value = c(min(FinalDF$PAtt), max(FinalDF$PAtt))),
sliderInput("Pyards",
"Passing Yards",
min = min(FinalDF$PYds),
max = max(FinalDF$PYds),
value = c(min(FinalDF$PYds), max(FinalDF$PYds))),
sliderInput("Ptds",
"Passing TD's",
min = min(FinalDF$PTD),
max = max(FinalDF$PTD),
value = c(min(FinalDF$PTD), max(FinalDF$PTD))),
sliderInput("RuAttempts",
"Rushing Attempts",
min = min(FinalDF$RuAtt),
max = max(FinalDF$RuAtt),
value = c(min(FinalDF$RuAtt), max(FinalDF$RuAtt))),
sliderInput("RuYards",
"Rushing Yards",
min = min(FinalDF$RuYds),
max = max(FinalDF$RuYds),
value = c(min(FinalDF$RuYds), max(FinalDF$RuYds))),
sliderInput("RuYperA",
"Yards per Rushing Attempt",
min = min(FinalDF$RuYA),
max = max(FinalDF$RuYA),
value = c(min(FinalDF$RuYA), max(FinalDF$RuYA))),
sliderInput("RuTDs",
"Rushing TD's",
min = min(FinalDF$RuTD),
max = max(FinalDF$RuTD),
value = c(min(FinalDF$RuTD), max(FinalDF$RuTD))),
sliderInput("rec",
"Receptions",
min = min(FinalDF$Rec),
max = max(FinalDF$Rec),
value = c(min(FinalDF$Rec), max(FinalDF$Rec))),
sliderInput("ReYards",
"Receiving Yards",
min = min(FinalDF$ReYds),
max = max(FinalDF$ReYds),
value = c(min(FinalDF$ReYds), max(FinalDF$ReYds))),
sliderInput("ReYperA",
"Yards per Reception",
min = min(FinalDF$ReYA),
max = max(FinalDF$ReYA),
value = c(min(FinalDF$ReYA), max(FinalDF$ReYA))),
sliderInput("ReTDs",
"Receiving TD's",
min = min(FinalDF$ReTD),
max = max(FinalDF$ReTD),
value = c(min(FinalDF$ReTD), max(FinalDF$ReTD))),
sliderInput("fumb",
"Fumbles",
min = min(FinalDF$Fmb),
max = max(FinalDF$Fmb),
value = c(min(FinalDF$Fmb), max(FinalDF$Fmb))),
sliderInput("ppr",
"1 PPR Total Points",
min = min(FinalDF$PPR),
max = max(FinalDF$PPR),
value = c(min(FinalDF$PPR), max(FinalDF$PPR)))
),
#Main Panel
mainPanel(
selectInput("plottype",
"Which Plot",
choices = c("PPR by Player",
"PPR by Team",
"PPR by Age")),
plotOutput("plot1"),
tableOutput("table"),
verbatimTextOutput("minmax")
)
)
)
######################################################################
#--------------------------------Server------------------------------#
######################################################################
server <- function(input, output) {
#Reactive to subset data and reduce size in graps
df <- reactive({
a = subset(FinalDF,
FantPos = input$position,
Player = input$playername,
Team = input$team,
Age >= input$age[1] & Age <= input$age[2],
Cmp >= input$completions[1] & Cmp <= input$completions[2],
PAtt >= input$Pattempts[1] & PAtt <= input$Pattempts[2],
PYds >= input$Pyards[1] & PYds <= input$Pyards[2],
PTD >= input$Ptds[1] & PTD <= input$Ptds[2],
RuYA >= input$RuYperA[1] & RuYA <= input$RuYperA[2],
RuAtt >= input$RuAttempts[1] & RuAtt <= input$RuAttempts[2],
RuYds >= input$RuYards[1] & RuYds <= input$RuYards[2],
RuTD >= input$RuTDs[1] & RuTD <= input$RuTDs[2],
Rec >= input$rec[1] & Rec <= input$rec[2],
ReYds >= input$ReYards[1] & ReYds <= input$ReYards[2],
ReYA >= input$ReYperA[1] & ReYA <= input$ReYperA[2],
ReTD >= input$ReTDs[1] & ReTD <= input$ReTDs[2],
Fmb >= input$fumb[1] & Fmb <= input$fumb[2],
PPR >= input$ppr[1] & PPR <= input$ppr[2]
)
return(a)
})
#Plot
output$plot1 <- renderPlot({
# generate bins based on input$bins from ui.R
if(input$plottype == "PPR by Player"){
ggplot(data = df()) +
geom_point(data = df(),
aes(x = Player,
y = PPR,
color = FantPos)) +
ggtitle("PPR Points") +
xlab("Player") +
ylab("PPR Points")
}
else if(input$plottype == "PPR by Team"){
ggplot(data = df()) +
geom_point(data = df(),
aes(x = Team,
y = PPR,
color = FantPos)) +
ggtitle("PPR Points") +
xlab("Player") +
ylab("PPR Points")
}
else if(input$plottype == "PPR by Age"){
ggplot(data = df()) +
geom_point(data = df(),
aes(x = Age,
y = PPR,
color = FantPos)) +
ggtitle("PPR Points") +
xlab("Player") +
ylab("PPR Points")
}
})
#Checking inputs
output$minmax <- renderText(
paste("age", input$age[1], input$age[2], "\ncompletions =",
input$completions[1],input$completions[2],"\nPattempts =",
input$Pattempts[1],input$Pattempts[2],"\nPyards =",
input$Pyards[1],input$Pyards[2],"\nPtds =",
input$Ptds[1],input$Ptds[2],"\nRuYperA =",
input$RuYperA[1],input$RuYperA[2],"\nRuAttempts =",
input$RuAttempts[1],input$RuAttempts[2],"\nRuYards =",
input$RuYards[1],input$RuYards[2],"\nRuTDs =",
input$RuTDs[1],input$RuTDs[2],"\nrec =",
input$rec[1],input$rec[2],"\nReYards =",
input$ReYards[1],input$ReYards[2],"\nReYperA =",
input$ReYperA[1],input$ReYperA[2],"\nReTDs =",
input$ReTDs[1],input$ReTDs[2],"\nfumb =",
input$fumb[1],input$fumb[2],"\nppr =",
input$ppr[1], input$ppr[2])
)
}
# Run the application
shinyApp(ui = ui, server = server)

My apologies. I will be sure to include a reproducible example next time. I replicated the code by making a smaller DataFrame. The replicated code and it worked, so I had another look at my original data. There was a column that was NA at the end. When renaming the columns I forgot the index at the end. I also changed from subset to filter. Not sure why the last column with no name messed everything up, but the shiny ran how I wanted after those changes.

Related

ShinyApp in R - Contrast Error of having Factor of level 1 with Radiobutton Inputs

I'm building a Shiny Application using R , basically it takes a dataset and runs it through several models - Classification / Regression.
The problem i am facing now is , I take inputs from the user with some being numeric and some being factors. The Factor inputs always have one level since we are using Radiobuttons to select a value.
radioButtons("HomeOwner", "Does the Customer own a home?", choiceNames=c('Yes', 'No'), choiceValues = c(1,0)),
radioButtons("Debt", "Does the Customer has existing debt?", choiceNames=c('Yes', 'No'), choiceValues = c(1,0)),
So my dataframe from the building the model has Factors for 3 variables and so does my input data frame from the user but the levels are one since i need to know if they select Yes or No.
Below is the Dataframe :
When i try to predict using the model created , i get the contrast error because of my input dataframe having factor of 1 in three variables , i need them to be factors or is there any way to solve this?
Edit 1 : Whole App
# Application Start
# Initiating Library
source("Functions.R")
library(shiny)
library(shinythemes)
#########################Start of ShinyApp Code#######################################
# Install the shiny and shinythemes packages
# install.packages('shiny')
# install.packages('shinythemes')
# Create the user interface (ui) where you will take the input and display the output
#ui <- fluidpage()
ui <- fluidPage(shinythemes::themeSelector(),
titlePanel("Assignment-AIPM"),
sidebarLayout(
sidebarPanel(
selectInput("selectds","Select the dataset to work with",
choices = c("Boston Housing Dataset"=1,
"Customer Profit Dataset"=2,
"Financial Dataset"=3,
"Education Tech Dataset"=4)
),
br(),
actionButton("runmodels","Run Models"),
),
mainPanel(
navbarPage("Information",
tabPanel("Input",uiOutput("myInput")),
tabPanel("Output",tableOutput("myOutput")),
tabPanel("Plots",plotOutput("myPlot"))
)
)
)
) # fluidPage
# https://stackoverflow.com/questions/30906325/shiny-use-column-headers-from-read-in-file-as-selectinput-choices - To select
# Input from a datapath using the columns
# https://stackoverflow.com/questions/54205476/how-to-execute-a-function-in-the-shiny-server-depending-on-the-inputid-value-of/54220548
# Function Execution
# Define server function
server <- function(input, output, session)
{
observeEvent(input$runmodels,
{
############################# Boston House Prediction
if(input$selectds == 1 )
{
print("Entering Boston House Prediction Input")
output$myInput <- renderUI({
tagList(tags$h3("Enter the details of the Land:"),
radioButtons("CHAS", "Near Charles River or Not", choiceNames=c('Yes', 'No'), choiceValues = c('1','0')),
numericInput("CRIM", "Criminal Rate 1 - 5", 1, min=1, max=5),
numericInput("ZN", "Proportion of Land Zone over 25,000 SQFT", 1),
numericInput("INDUS", "Proportion of Industrial Business in the town", 1),
numericInput("RM", "Average Number of Rooms Per Dwelling", 1),
numericInput("NOX", "Tenure in No. of Years", 1),
numericInput("AGE", "Proportion of Owner Occupied Buildings prior 1940", 1),
numericInput("DIS", "Weighted Distances to Boston Employment Centre", 1),
numericInput("RAD", "Radial Access to highways", 1),
numericInput("TAX", "Full Value Property rate per 10,000$", 1),
numericInput("PTRATIO", "Pupil - Teacher Ratio in Town", 1),
numericInput("B", "Proportion of Black Population in Town", 1),
numericInput("LSTAT", "Percentage of Lower Status Population", 1),
HTML("<br> <br>")
)
})
data_input = reactive({
data.frame(CHAS = factor(input$CHAS),
CRIM = input$CRIM,
ZN = input$ZN,
INDUS = input$INDUS,
NOX = input$NOX,
RM = input$RM,
AGE = input$AGE,
DIS = input$DIS,
RAD = input$RAD,
TAX = input$TAX,
PTRATIO = input$PTRATIO,
B = input$B,
LSTAT = input$LSTAT)
})
regressor_linear <- boston_linear_reg()
data_output = reactive({
data.frame(Logistic_regression = predict(regressor_linear,type='response',data_input())
)
})
output$myOutput <- renderTable({data_output()})
}
############################################### Customer Profit
if(input$selectds == 2 )
{
print("Entering Customer Profit User Input")
output$myInput <- renderUI({
tagList(tags$h3("Enter the details of the customer:"),
radioButtons("Online", "Online Customer?", choiceNames=c('Yes', 'No'), choiceValues = c('1','0')),
radioButtons("Age", "Whats your Customer Age Group?", choiceNames=c('0-10','10-20','20-30','30-40','40-50','50-60','60-70'), choiceValues = c('1','2','3','4','5','6','7')),
radioButtons("Income", "Whats your Customer Income Group?", choiceNames=c('5k-10k','10k-15k','15k-20k','20k-25k','25k-30k','30k-35k','35k-40k','40k-50k','50k+'), choiceValues = c('1','2','3','4','5','6','7','8','9')),
numericInput("Tenure", "Tenure in No. of Years", 1),
HTML("<br> <br>"))
})
data_input = reactive({
data.frame(Online = as.integer(input$Online),
Age = as.integer(input$Age),
Inc = as.integer(input$Income),
Tenure = as.numeric(input$Tenure))
})
regressor_linear <- customer_linear_reg()
classifier_Rforest <- customer_RForest_Regression()
classifier_NNet <- customer_NeuralNet()
data_output = reactive({
data.frame(Linear_regression = predict(regressor_linear,data_input()),
Random_Forest_Prediction = predict(classifier_Rforest,data_input()),
Neural_Net_Prediction = as.data.frame(h2o.predict(classifier_NNet, newdata = as.h2o(data_input())))
)
})
output$myOutput <- renderTable({data_output()})
}
########################## Financial set
if(input$selectds == 3 )
{
print("Entering Finanical User Input")
output$myInput <- renderUI({
tagList(numericInput("Age", "Please enter the Customer Age(1-100)", 25, min=1, max=100),
numericInput("Income", "Please enter Customer monthly Income(0-100000$)", 3500, min=0, max=100000),
radioButtons("HomeOwner", "Does the Customer own a home?", choiceNames=c('Yes', 'No'), choiceValues = c(1,0)),
radioButtons("Debt", "Does the Customer has existing debt?", choiceNames=c('Yes', 'No'), choiceValues = c(1,0)),
numericInput("EmpPeriod", "Please enter the Customer employement period in months", 45),
numericInput("AccPeriod", "Please enter Customer Account Age in months",45),
numericInput("Amount", "Please enter Amount Requested($)",1000),
radioButtons("PaySchedule", "Please enter Pay Schedule", choiceNames=c('bi-weekly', 'weekly', 'semi-monthly','monthly'), choiceValues = c(1,2,3,4)),
numericInput("CurrAddress", "Please enter the Customer currnt address period in months", 45),
numericInput("RiskScore", "Please enter Customer Risk Score (1-100000",40000),
numericInput("Enquiry", "Please enter Customer enquiries last month",5),
actionButton("Predict", "Predict Sanction"))
})
observeEvent(input$Predict, {
data_input = reactive({
data.frame(
home_owner = factor(input$HomeOwner),
age = as.numeric(input$Age),
income = as.numeric(input$Income),
has_debt = factor(input$Debt),
amount_requested = input$Amount,
employment_period = input$EmpPeriod,
personal_account_period = input$AccPeriod,
pay_schedule = factor(input$PaySchedule),
current_address_period = input$CurrAddress,
inquiries_last_month = as.integer(input$Enquiry),
risk_score = input$RiskScore
)
})
logistic_regressor = financial_logistic_regression()
Single_DT = financial_DT()
#classifier_svm = financial_svm()
str(data_input())
data_output = reactive({
data.frame(Logistic_regression = predict(logistic_regressor,type='response',newdata=data_input()),
#Support_vector_machine = predict(classifier_svm, type = 'response', newdata = data_input())
Single_Decision_Tree = predict(Single_DT$classifier, type = 'class', newdata = data_input())
)
})
output$myPlot <- renderPlot({rpart.plot::rpart.plot(Single_DT$classifier)})
output$myOutput <- renderTable({data_output()})
})
}
Functions.R
#Functions for Shiny Assignement
library(caret)
library(ROCR)
library(Metrics)
library(dplyr)
library(caTools)
library(e1071)
library(zoo)
library(car)
library(rpart)
library(randomForest)
library(rpart.plot)
library(h2o)
library(data.table)
# Global Datasets
bostonds <- read.csv('Datasets/02_Boston.csv')
customerds <- read.csv('Datasets/01_CustomerProfit_Regression.csv')
financialds <- read.csv('Datasets/04_P39_Financial_Data.csv')
edtechds <- read.csv('Datasets/05_Lead_Scoring.csv')
boston_linear_reg <- function()
{
set.seed(1234)
data_nomiss = bostonds %>% select(CRIM,ZN,INDUS,CHAS,NOX,RM,AGE,DIS,RAD,
TAX,PTRATIO,B,LSTAT,MEDV) %>% na.omit()
data_nomiss$CHAS = factor(data_nomiss$CHAS)
regressor_lm = lm(formula = MEDV ~ .,data=data_nomiss)
return(regressor_lm)
#medv_predict = predict(regressor,test_ds)
}
customer_linear_reg <- function()
{
data_nomiss = customerds %>% select(Profit,Online,Age,Inc,Tenure) %>% na.omit()
#data_nomiss$Online = factor(data_nomiss$Online)
set.seed(123)
regressor_lm = lm(formula = Profit ~ Online + Inc + Age + Tenure
, data = data_nomiss,na.action = na.omit)
str(data_nomiss)
return(regressor_lm)
#profit_predict = predict(regressor, newdata=test_set)
}
customer_RForest_Regression <- function()
{
######## Data Processing and Cleanup starts here
dataset = customerds
# Creating a new dataset called 'data_nomiss' which will have no missing data
data_nomiss = dataset %>%
select(Profit,Online,Age,Inc,Tenure) %>%
na.omit()
#data_nomiss$Online = factor(data_nomiss$Online)
#data_nomiss$Age = factor(data_nomiss$Age, labels = c('0-10','10-20','20-30','30-40','40-50','50-60','60-70'),levels = c('1','2','3','4','5','6','7'))
#data_nomiss$Inc = factor(data_nomiss$Inc, labels = c('5k-10k','10k-15k','15k-20k','20k-25k','25k-30k','30k-35k','35k-40k','40k-50k','50k+'),levels = c('1','2','3','4','5','6','7','8','9'))
# Factor Variables
#data_nomiss[,1] = scale(data_nomiss[,1])
#data_nomiss[,5] = scale(data_nomiss[,5])
########### Data Processing and Cleanup ends here
set.seed(123)
classifier = randomForest(Profit ~ .,data=data_nomiss,na.action = na.omit,ntree=100)
return(classifier)
}
customer_NeuralNet <- function()
{
dataset = customerds
data_nomiss = dataset %>%
select(Profit,Online,Age,Inc,Tenure) %>%
na.omit()
set.seed(123)
h2o.init(nthreads = -1)
classifier = h2o.deeplearning(y = 'Profit',
training_frame = as.h2o(data_nomiss),
activation = 'Tanh',
hidden = c(10),
epochs = 100,
train_samples_per_iteration = -2)
return(classifier)
}
############################### Financial Dataset
financial_pre_process <- function(ds)
{
####################Data Processing and Clean up Start#############################
data_nomiss = ds %>% select(age,pay_schedule,home_owner,income,
months_employed,years_employed,current_address_year,
personal_account_m,personal_account_y,has_debt,
amount_requested,risk_score,risk_score_2,
risk_score_3,risk_score_4,risk_score_5,
ext_quality_score,ext_quality_score_2,
inquiries_last_month,e_signed) %>% na.omit()
data_nomiss$e_signed = factor(data_nomiss$e_signed)
data_nomiss$home_owner = factor(data_nomiss$home_owner)
data_nomiss$has_debt = factor(data_nomiss$has_debt)
data_nomiss$pay_schedule = factor(data_nomiss$pay_schedule,
levels = c('weekly','bi-weekly','monthly','semi-monthly'),
labels = c(1,2,3,4))
data_nomiss$employment_period = data_nomiss$months_employed + (data_nomiss$years_employed * 12)
data_nomiss$personal_account_period = data_nomiss$personal_account_m + (data_nomiss$personal_account_y * 12)
data_nomiss$current_address_period = data_nomiss$current_address_year * 12
data_nomiss = select(data_nomiss,-c(months_employed,years_employed,personal_account_m,personal_account_y,current_address_year))
data_nomiss[,1] = scale(data_nomiss[,1]) # Age
data_nomiss[,4] = scale(data_nomiss[,4]) # Income
data_nomiss[,6:14] = scale(data_nomiss[,6:14]) # Amount Requested -> Risk score
data_nomiss[,16:18] = scale(data_nomiss[,16:18]) # Created Columns
data_nomiss[,1] = apply(data_nomiss[,1], 1, as.numeric)
data_nomiss[,4] = apply(data_nomiss[,4], 1, as.numeric)
return(data_nomiss)
####################Data Processing and Clean up End#############################
}
financial_logistic_regression <- function()
{
ds = financialds
set.seed(1234)
data_nomiss = financial_pre_process(ds)
str(data_nomiss)
classifier_log = glm(formula = e_signed ~ age+pay_schedule+current_address_period+home_owner+income+employment_period+has_debt+amount_requested+personal_account_period+risk_score+inquiries_last_month,
family = binomial,
data = data_nomiss)
return(classifier_log)
}
financial_svm <- function()
{
ds = financialds
set.seed(1234)
data_nomiss = financial_pre_process(ds)
classifier_svm = svm(formula = e_signed ~ age+pay_schedule+current_address_period+home_owner+income+employment_period+has_debt+amount_requested+personal_account_period+risk_score+inquiries_last_month,
data = data_nomiss,
type = 'C-classification',
kernel = 'radial')
return(classifier_svm)
}
financial_DT <- function()
{
ds = financialds
set.seed(1234)
data_nomiss = financial_pre_process(ds)
classifier_DT = rpart(formula = e_signed ~ age+pay_schedule+current_address_period+home_owner+income+employment_period+has_debt+amount_requested+personal_account_period+risk_score+inquiries_last_month,
data = data_nomiss)
result <- list()
result$classifier <- classifier_DT
result$plot <- rpart.plot::rpart.plot(classifier_DT)
return(result)
}
financial_RForest <- function()
{
ds = financialds
set.seed(1234)
data_nomiss = financial_pre_process(ds)
classifier_RForest = randomForest(x= training_set[-15],
y= training_set$e_signed,
ntree=1500)
result <- list()
result$classifier <- classifier_RForest
result$plot <- rpart.plot::rpart.plot(classifier_RForest)
return(result)
}
}

Reactive Data Issues in RShiny

I'm working on a Shiny dashboard for a personal project with some football stats. Whenever I change the statistic to be graphed and/or the filter, I get the same players that were in the first dataset. For example, when I start the app, the app creates a graph of the top ten rushers in school history with a filter of rushing attempts >= 0. When I change the statistic selection to rushing average, however, those ten players are the ones shown, which is incorrect.
library(readxl)
library(tidyverse)
library(purrr)
library(shiny)
interface <- fluidPage(
titlePanel(" "),
sidebarLayout(
sidebarPanel(
h1("Stats!"),
selectInput("stat_selection",
label = "Select a season statistics",
choices = c("Rushing Yards",
"Rushing Touchdowns",
"Rushing Average",
"Reciving Yards",
"Receptions",
"Receiving Touchdowns",
"Receiving Average"),
selected = "Rushing Yards"),
selectInput("filter_input",
label = "Select a statistic to filter by",
choices = c("Rushing Yards",
"Rushing Touchdowns",
"Rushing Average",
"Rushing Attempts",
"Reciving Yards",
"Receptions",
"Receiving Touchdowns",
"Receiving Average"),
selected = "Rushing Attempts"),
numericInput("filter_number",
label = "Type a number for the filter (>=)",
value = 0, min = 0),
actionButton("button", "Graph")),
mainPanel(
plotOutput("plot_button"),
tableOutput("table_button")
)
)
)
server_osu <- function(input, output) {
dataInput <- reactive({
switch(input$stat_selection,
"Rushing Yards" = rush_yds,
"Rushing Touchdowns" = rush_tds,
"Rushing Average" = rush_avg,
"Reciving Yards" = rec_yds,
"Receptions" = rec_rec,
"Receiving Touchdowns" = rec_td,
"Receiving Average" = rec_avg)
})
filterInput <- reactive({
switch(input$filter_input,
"Rushing Yards" = rush_yds,
"Rushing Touchdowns" = rush_tds,
"Rushing Average" = rush_avg,
"Rushing Attempts" = rush_att,
"Reciving Yards" = rec_yds,
"Receptions" = rec_rec,
"Receiving Touchdowns" = rec_td,
"Receiving Average" = rec_avg)
})
filter_number <- reactive(as.double(input$filter_number))
table_button_react <- eventReactive(input$button, {
dataset <- dataInput()
val <- filter_number()
colnames(dataset)[1] = "Player and Season"
dataset_filter <- filterInput()
colnames(dataset_filter)[1] = "Player and Season"
dataset <- left_join(dataset, dataset_filter)
colnames(dataset)[1] = "Player and Season"
og <- colnames(dataset)[3]
colnames(dataset)[3] = "filter"
original <- colnames(dataset)[2]
colnames(dataset)[2] = 'selected'
dataset <- dataset %>%
filter(filter >= val)
dataset <- dataset %>%
top_n(10) %>%
arrange(-selected)
colnames(dataset)[2] = original
colnames(dataset)[3] = og
dataset
})
plot_button_react <- eventReactive(input$button, {
dataset <- dataInput()
val <- filter_number()
colnames(dataset)[1] = "Player and Season"
dataset_filter <- filterInput()
colnames(dataset_filter)[1] = "Player and Season"
dataset <- left_join(dataset, dataset_filter)
colnames(dataset)[1] = "Player and Season"
colnames(dataset)[2] = "selected"
colnames(dataset)[3] = "filter"
dataset <- dataset %>%
filter(filter >= val)
top_ten <- dataset %>% top_n(10)
min = min(top_ten$selected)
max = max(top_ten$selected)
ggplot(top_ten, aes(x = reorder(`Player and Season`, -selected), y = selected)) +
geom_bar(stat = 'identity') + theme_minimal() + xlab('SEASON') +
ylab(input$stat_selection) + theme(text=element_text(size=16)) +
scale_fill_manual(values = c('#BBBBBB', '#BB0000')) +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
theme(legend.position = 'none') +
coord_cartesian(ylim=c(min - 0.05*min, max + 0.05*max)) +
theme(axis.title.y = element_text(margin = margin(t = 0, r = 10, b = 0, l = 10))) +
theme(axis.title.x = element_text(margin = margin(t = 10, r = 0, b = 10, l = 0))) +
theme(axis.text.y = element_text(size=14),
axis.title=element_text(size=16,face='bold')) +
labs(caption = '')
})
output$plot_button <- renderPlot({
plot_button_react()
})
output$table_button <- renderTable({
table_button_react()
})
}
As I mentioned above, a reprex - including input data - would help us to help you. That said, I think the problem is that your XXX_button_reacts depend only on input$button. They don't depend on input$stat_selection, input$filter_number or input$filter_input. That's why they don't update as you want them to.
The fix is easy. Just add them (in a call to req() if you like) at the top of each XXXX_button_react, for example:
plot_button_react <- eventReactive(input$button, {
input$stat_selection
input$filter_number
input$filter_input
<your code here>
})
As a point of style, I feel it's better to separate data generation from data presentation. It makes the logic of your code more obvious, reduces the chance of errors, reduces the need for code duplication and makes your code more reusable.
In your case, I would create a reactive that holds the data you wish to tablulate and plot and then reference that reactive in each of your render_XXXX functions. That would also remove the need for your input$button: the plot and graph would each update automatically whenever you changed one of your other input widgets.

Shiny app: Download data source outside of renderPlot for quicker user manipulation

This is my first shiny app. I would like for the user to be able to update the number of facet columns and the dimensions of downloaded plot. readNWISuv, the function to download data can take a long time if multiple years are queried. Currently, the app downloads the data each time the user wants to change the plot format or plot dimensions. Not sure if I need to use reactiveValues, but I would assume that I want the data to be downloaded and manipulated outside of renderPlot. Thanks!
library(shiny)
library(dataRetrieval)
library(lubridate)
library(tidyverse)
library(plotly)
#flow wrecker
ui <- pageWithSidebar( #fluidPage(
# Application title
titlePanel("Flow Record"),
# Sidebar with a date input
#sidebarLayout
sidebarPanel(
dateRangeInput("daterange", "Date range: (yyyy-mm-dd)",
start = Sys.Date()-10,
min = "1980-10-01"),
textInput("gage", "USGS Gage #", "11532500"),
#actionButton("dload","Download data"),
selectInput("facet_x", "Facet Column #:", 2, choices =1:4),
submitButton("Update View", icon("refresh")),
helpText("When you click the button above, you should see",
"the output below update to reflect the values you",
"entered above:"),
#verbatimTextOutput("value"),
downloadButton('downloadImage', 'Download figure'),
numericInput("fig_x", "Fig. Dim. x:", 10, min = 3, max = 16),
numericInput("fig_y", "Fig. Dim. y:", 10, min = 3, max = 16),
width = 3
),
# Show a plot of the generated WY
mainPanel(
plotlyOutput("WYfacet")
)
)
# Define server draw WY facets
server <- function(input, output) {
parameterCd <- "00060" # discharge
#water year
wtr_yr <- function(dates, start_month=10) {
# Convert dates into POSIXlt
dates.posix = as.POSIXlt(dates)
# Year offset
offset = ifelse(dates.posix$mon >= start_month - 1, 1, 0)
# Water year
adj.year = dates.posix$year + 1900 + offset
# Return the water year
adj.year
}
output$WYfacet <- renderPlotly({
#progress bar
withProgress(readNWISuv(input$gage, parameterCd, input$daterange[1], input$daterange[2],tz="America/Los_Angeles") %>% addWaterYear,
message = 'Download in progress',
detail = 'This may take a while...', value = 1)
#download
temperatureAndFlow <- readNWISuv(input$gage, parameterCd, input$daterange[1], input$daterange[2],tz="America/Los_Angeles") %>% addWaterYear
names(temperatureAndFlow)<-c("agc","site","date","WY", "flow","a","tzone")
temperatureAndFlow$commonDate <- as.Date(format(temperatureAndFlow$date, format="2000-%m-%d"))
tf.df<-temperatureAndFlow %>%
filter(WY<=max(WY) & WY>=if_else(month(min(date))<10,min(WY)+1,min(WY)))
tf.df$date.d<-format(tf.df$date, format="%Y-%m-%d")
#mutate commonDate
df4 <- tf.df %>%
mutate(WY=factor(wtr_yr(date.d))) %>%
#seq along dates starting with the beginning of your water year
mutate(commonDate=as.Date(paste0(ifelse(month(date.d) < 10, "2001", "2000"),
"-", month(date.d), "-", day(date.d))), Date=date.d)
#plot
ploty<-ggplot(data = df4,mapping = aes(x = commonDate, y = flow,label=Date, colour = factor(WY))) +
geom_line() +
labs(x = " ", y = "Discharge (cfs)") +
facet_wrap(facets = ~WY,ncol=as.integer(input$facet_x)) +
scale_y_log_eng()+
annotation_logticks(sides = "l")+
theme_bw()+
theme(panel.grid.minor.x = element_blank())+
scale_x_date(labels = function(x) format(x, "%b"),date_breaks = "1 months")+
guides(colour=FALSE)
ggplotly(ploty, tooltip=c("flow","Date"))
})
#fig dimensions
output$fig_x <- renderText({ input$fig_x })
output$fig_y <- renderText({ input$fig_y })
#facet columns
output$facet_x <- renderText({ input$facet_x })
#download to computer
output$downloadImage <- downloadHandler(
filename = function(){paste("plot",'.png',sep='')},
content = function(file){
ggsave(file,width = input$fig_x,height = input$fig_y, dpi = 600, units = "in", device='png')
print(ggplot(data = df4,mapping = aes(x = commonDate, y = flow, colour = factor(WY))) +
geom_line() +
#geom_point()+
#geom_vline(data = trip,aes(xintercept=commonDate),trip_df,color="black")+
labs(x = " ", y = "Discharge (cfs)") +
facet_wrap(facets = ~WY,ncol=as.integer(input$facet_x)) +
scale_y_log_eng()+
annotation_logticks(sides = "l")+
theme_bw()+
theme(panel.grid.minor.x = element_blank())+
scale_x_date(labels = function(x) format(x, "%b"),date_breaks = "1 months")+
guides(colour=FALSE))
})
}
# Run the application
shinyApp(ui = ui, server = server)
There are a few changes to make to your sever section to make this work. Primarily:
splitting the creation of the dataframe into a new eventReactive function, dependent on an actionButton.
referring to the function inside the renderPlotly call
Try this:
## Within ui function call ############################################
# submitButton("Update View", icon("refresh")), # line to replace
actionButton(inputId = "update", "Update View", icon("refresh")),
## (if you want to keep a button to control when data is downloaded ##
server <- function(input, output) {
parameterCd <- "00060" # discharge
#water year
wtr_yr <- function(dates, start_month=10) {
# Convert dates into POSIXlt
dates.posix = as.POSIXlt(dates)
# Year offset
offset = ifelse(dates.posix$mon >= start_month - 1, 1, 0)
# Water year
adj.year = dates.posix$year + 1900 + offset
# Return the water year
adj.year
}
# New part here - use `reactive` to make df4 a new thing, which is processed separately. The `eventReactive` function waits till it sees the button pressed.
df4 <- eventReactive(input$update, ignoreNULL = FALSE, {
#progress bar
withProgress(readNWISuv(input$gage, parameterCd, input$daterange[1], input$daterange[2],tz="America/Los_Angeles") %>% addWaterYear,
message = 'Download in progress',
detail = 'This may take a while...', value = 1)
#download
temperatureAndFlow <- readNWISuv(input$gage, parameterCd, input$daterange[1], input$daterange[2],tz="America/Los_Angeles") %>% addWaterYear
names(temperatureAndFlow)<-c("agc","site","date","WY", "flow","a","tzone")
temperatureAndFlow$commonDate <- as.Date(format(temperatureAndFlow$date, format="2000-%m-%d"))
tf.df<-temperatureAndFlow %>%
filter(WY<=max(WY) & WY>=if_else(month(min(date))<10,min(WY)+1,min(WY)))
tf.df$date.d<-format(tf.df$date, format="%Y-%m-%d")
#mutate commonDate
tf.df %>%
mutate(WY=factor(wtr_yr(date.d))) %>%
#seq along dates starting with the beginning of your water year
mutate(commonDate=as.Date(paste0(ifelse(month(date.d) < 10, "2001", "2000"),
"-", month(date.d), "-", day(date.d))), Date=date.d)
})
output$WYfacet <- renderPlotly({
# req will pause plot loading till new data downloaded above, but changes to display will render without new download
req(df4())
#plot
ploty<-ggplot(data = df4(), # Put brackets here to refer to df4 as a reactive input!!!
mapping = aes(x = commonDate, y = flow, label=Date, colour = factor(WY))) +
geom_line() +
labs(x = " ", y = "Discharge (cfs)") +
facet_wrap(facets = ~WY,ncol=as.integer(input$facet_x)) +
scale_y_log10()+
# annotation_logticks(sides = "l")+
theme_bw()+
theme(panel.grid.minor.x = element_blank())+
scale_x_date(labels = function(x) format(x, "%b"),date_breaks = "1 months")+
guides(colour=FALSE)
ggplotly(ploty, tooltip=c("flow","Date"))
})
#fig dimensions
output$fig_x <- renderText({ input$fig_x })
output$fig_y <- renderText({ input$fig_y })
#facet columns
output$facet_x <- renderText({ input$facet_x })
#download to computer
output$downloadImage <- downloadHandler(
filename = function(){paste("plot",'.png',sep='')},
content = function(file){
ggsave(file,width = input$fig_x,height = input$fig_y, dpi = 600, units = "in", device='png')
print(ggplot(data = df4() ,mapping = aes(x = commonDate, y = flow, colour = factor(WY))) +
geom_line() +
#geom_point()+
#geom_vline(data = trip,aes(xintercept=commonDate),trip_df,color="black")+
labs(x = " ", y = "Discharge (cfs)") +
facet_wrap(facets = ~WY,ncol=as.integer(input$facet_x)) +
scale_y_log10()+
annotation_logticks(sides = "l")+
theme_bw()+
theme(panel.grid.minor.x = element_blank())+
scale_x_date(labels = function(x) format(x, "%b"),date_breaks = "1 months")+
guides(colour=FALSE))
})
}

Shiny save as pdf or plot

Here is my code I have 3 different questions, I searched evrywhere and tryied sooo many things, but it always gave me an error .
First how can I add a function to save my rglwidgetoutput to any file ?
And also mby save the log .
Secound: If I open the program it always opens a small "focus" window, can I somehow remove that ?
And last but not least, I have a Log , and I want to rename the data_planes so the logfile looks better :)
#######################################################################################
# Install librarys #
#######################################################################################
#install.packages("shiny")
#install.packages("rgl")
#install.packages("shinythemes")
#install.packages("devtools")
library(shiny)
library(rgl)
library(shinythemes)
library(devtools)
#install_github("rgl", "trestletech", "js-class")
#install_github("rgl", "trestletech", "js-class")
#######################################################################################
# User Interface #
#######################################################################################
ui <- fluidPage(theme = shinytheme("slate"),
headerPanel("Block Theory"),
sidebarPanel(
numericInput(inputId = "dd", label = "Dip direction:", value = "", width = "80%", min = 0, max = 360),
numericInput(inputId = "fa", label = "Fracture angle:", value = "", width = "80%", min = 0, max = 90),
numericInput(inputId = "position_x", label = "Position:", value = "", width = "40%"),
numericInput(inputId = "position_y", label = "", value = "", width = "40%"),
numericInput(inputId = "position_z", label = "", value = "", width = "40%"),
#selectInput("form", "Form:",
# c("Circle", "Square", "Ellipsoid")),
actionButton(inputId = "add", label = "Add a plane"),
actionButton(inputId = "plotbutton", label = "Update")
),
mainPanel(
tabsetPanel(
tabPanel("Plot", rglwidgetOutput(outputId = "plot")), # Output
tabPanel("Log", verbatimTextOutput(outputId = "log_planes")), # Log File
# OPTIONS :
tabPanel("Preferences",
checkboxInput("axes_lim", "axes min / max"),
conditionalPanel(
condition = "input.axes_lim == true",
splitLayout(
numericInput(inputId = "min_x", label = "x min:", value = "0", width = "90%"),
numericInput(inputId = "max_x", label = "x max:", value = "1000", width = "90%")),
splitLayout(
numericInput(inputId = "min_y", label = "y min:", value = "0", width = "90%"),
numericInput(inputId = "max_y", label = "y max:", value = "1000", width = "90%")),
splitLayout(
numericInput(inputId = "min_z", label = "z min:", value = "0", width = "90%"),
numericInput(inputId = "max_z", label = "z max:", value = "1000", width = "90%"))),
checkboxInput("axes", "Change axes ratio"),
conditionalPanel(
condition = "input.axes == true",
sliderInput("x_axis", "x axis:",min = 0, max = 1, value = 1, step = 0.1),
sliderInput("y_axis", "y axis:",min = 0, max = 1, value = 1, step = 0.1),
sliderInput("z_axis", "z axis:",min = 0, max = 1, value = 1, step = 0.1)),
checkboxInput("theme", "Change shiny theme"),
conditionalPanel(
condition = "input.theme == true",
shinythemes::themeSelector() )
))
) # /Main panel
) # /ui
#######################################################################################
# SERVER #
#######################################################################################
server <- function(input, output) {
data_planes <- data.frame()
makeReactiveBinding("data_planes")
observe({
input$add
isolate({
data_planes <<- rbind(data_planes, data.frame(input$dd, input$fa , input$position_x , input$position_y , input$position_z))
data_planes <<- na.omit(data_planes)
})
})
output$plot <- renderRglwidget({
input$plotbutton
isolate({
####################################################
# Open 3d plot:
x<-sample(input$min_x:input$max_x, 100)
y<-sample(input$min_y:input$max_y, 100)
z<-sample(input$min_z:input$max_z, 100)
plot3d(x, y, z, type = "n",xlim = c(min(x), max(x)), ylim = c(min(y), max(y)), zlim = c(min(z), max(z),expand = 1.03))
aspect3d(input$x_axis , input$y_axis , input$z_axis)
####################################################
i=1;
while (i <= nrow(data_planes)) {
phi <- data_planes[i,1] * pi / 180
theta <- data_planes[i,2] * pi / 180
Px <- data_planes[i,3]
Py <- data_planes[i,4]
Pz <- data_planes[i,5]
n <- c(sin(theta)*sin(phi), sin(theta) * cos(phi), cos(theta))
# n <- c(-sin(theta)*sin(phi), sin(theta) * cos(phi), -cos(theta))
P_n <- cos(phi)*sin(theta)*Px+(sin(phi)*sin(theta))*Py+cos(phi)*Pz # d = -P * n
# planes3d() plots equation: a*x + b*y + c*z + d = 0
a <- -sin(theta)*sin(phi)
b <- sin(theta) * cos(phi)
c <- -cos(theta)
d <- P_n
cols<-rgb(runif(5),runif(5),runif(5)) #random color genarator
i <- i + 1
planes3d(a, b, c , d , col = cols, alpha = 0.6)
}
rglwidget() # opens the plot inside of main panel
})
})
output$log_planes <- renderPrint(data_planes)
}
#######################################################################################
shinyApp(ui = ui, server = server
)
It's not easy to save rgl output to a PDF. You can save it to an html page using code like this:
htmlwidgets::saveWidget(rglwidget(), file = "rgl.html")
This will fail if it can't find Pandoc; you can use
htmlwidgets::saveWidget(rglwidget(), file = "rgl.html", selfcontained = FALSE)
without Pandoc, but it will create both the HTML file and a subdir of supporting files.
The little window you're seeing is probably the rgl output window. If you never want to see that, run
options(rgl.useNULL = TRUE)
before loading the rgl package. This is a good idea on a Shiny app, because they may be running on a server somewhere and you don't want to try to open an rgl window there.
Sorry, I don't really understand your third question.

multiple selection in checkboxGroupInput and plotting in shiny

In my shiny app I have a checkboxGroupInput
How should I do the plot command in server function, in a way that I plot the TurbInt_mean against MeanWindSpeed_mean and add lines (curves) to the plot by user selection ?
I have tried to summaries my shiny app as reproduce-able code as follow (you have to first load the sample data that I have provided)
library(shiny)
ui <- fluidPage(
checkboxGroupInput("variable", "Select IEC Classes for TI",c("A Plus" = "ap","A" = "a","B" = "b","C"="c")),
plotOutput("plotmeanTI",width = "100%") )
server <- function(input, output, session){
output$plotmeanTI <- renderPlot({
plot(as.matrix(TI_plot[,1]),as.matrix(TI_plot[,2]),t='o',ylim=c(0,1),xaxs="i",
xlab="Mean Wind Speed", ylab="<TI>")
if(input$variable=="ap"){lines(as.matrix(TI_plot[,1]),TI_plot$NTM_A_Plus_mean,col=6)}
if(input$variable=="a"){lines(as.matrix(TI_plot[,1]),TI_plot$NTM_A_mean,col=2)}
if(input$variable=="b"){lines(as.matrix(TI_plot[,1]),TI_plot$NTM_B_mean,col=3)}
if(input$variable=="c"){lines(as.matrix(TI_plot[,1]),TI_plot$NTM_C_mean,col=4)}
})
}
shinyApp(ui=ui,server=server)
If user select 1, one curve should be added, if select more than one, I want to have multiple curves added to my plot.I can do it for single selection like I have explained in my code, but when I have multi selection it does not work.
My data set looks like :
dput(TI_plot)
structure(list(MeanWindSpeed_mean = c(0.292023070097604, 1.12011882699226,
2.0283906614786, 3.00947886508396, 4.01428066037736, 5.01250749719984,
6.0080377166157, 7.00777409860191, 8.0049941822883, 9.00201938353988,
9.99646762244478, 10.9883558855227, 11.9798700705476, 12.976996101646,
13.9653724394786, 14.9495068163593, 15.9628459343795, 16.9708685581934,
17.9623943661972, 18.992621231979, 19.9643220338983, 20.9834693877551,
22.0170278637771, 22.9658904109589, 24.0025266903915, 24.9935025380711
), TurbInt_mean = c(3.02705430346051, 0.420402191213343, 0.264195029831388,
0.215109260166585, 0.18794121258946, 0.16699392997796, 0.148261539245668,
0.134479958525654, 0.122038442146089, 0.110595865904036, 0.097103704211826,
0.0836329541372291, 0.0708397249149876, 0.0622491842333237, 0.0591184473929236,
0.0611678829190056, 0.0652080242510699, 0.0690131441806601, 0.073762588028169,
0.0756961992136304, 0.0805696610169492, 0.0817446428571429, 0.0830263157894737,
0.0827277397260274, 0.0749537366548043, 0.0765532994923858),
NTM_A_Plus_mean = c(Inf, 1.10260388189292, 0.642329939163608,
0.473065816856713, 0.387417559923049, 0.336769624752903,
0.303163441845455, 0.27908457313955, 0.261084722917897, 0.247090026094941,
0.235918715179959, 0.226796351934008, 0.219190019655214,
0.212713243118379, 0.20720881268079, 0.202452008587075, 0.19816685602934,
0.19441329542209, 0.191131377464549, 0.188086340606011, 0.185500707351721,
0.18304730715887, 0.180790073836667, 0.178898058874634, 0.177002145398197,
0.175335040729601), NTM_A_mean = c(Inf, 0.98009233946037,
0.570959945923208, 0.420502948317078, 0.344371164376044,
0.299350777558136, 0.269478614973738, 0.248075176124045,
0.232075309260353, 0.219635578751059, 0.209705524604408,
0.201596757274674, 0.194835573026857, 0.189078438327448,
0.184185611271814, 0.179957340966289, 0.176148316470525,
0.172811818152969, 0.169894557746266, 0.167187858316455,
0.164889517645975, 0.162708717474551, 0.160702287854815,
0.159020496777452, 0.157335240353953, 0.155853369537423),
NTM_B_mean = c(Inf, 0.857580797027824, 0.499589952682807,
0.367940079777444, 0.301324768829038, 0.261931930363369,
0.23579378810202, 0.217065779108539, 0.203065895602809, 0.192181131407176,
0.183492334028857, 0.176397162615339, 0.1704811263985, 0.165443633536517,
0.161162409862837, 0.157462673345503, 0.154129776911709,
0.151210340883848, 0.148657738027983, 0.146289376026898,
0.144278327940228, 0.142370127790232, 0.140614501872963,
0.139142934680271, 0.137668335309708, 0.136371698345246),
NTM_C_mean = c(Inf, 0.735069254595278, 0.428219959442406,
0.315377211237809, 0.258278373282033, 0.224513083168602,
0.202108961230303, 0.186056382093034, 0.174056481945265,
0.164726684063294, 0.157279143453306, 0.151197567956005,
0.146126679770143, 0.141808828745586, 0.13813920845386, 0.134968005724717,
0.132111237352894, 0.129608863614727, 0.127420918309699,
0.125390893737341, 0.123667138234481, 0.122031538105913,
0.120526715891111, 0.119265372583089, 0.118001430265464,
0.116890027153068)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -26L), .Names = c("MeanWindSpeed_mean",
"TurbInt_mean", "NTM_A_Plus_mean", "NTM_A_mean", "NTM_B_mean",
"NTM_C_mean"))
the head of TI_plot is like :
head(TI_plot)
# A tibble: 6 x 6
MeanWindSpeed_mean TurbInt_mean NTM_A_Plus_mean NTM_A_mean NTM_B_mean NTM_C_mean
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0.2920231 3.0270543 Inf Inf Inf Inf
2 1.1201188 0.4204022 1.1026039 0.9800923 0.8575808 0.7350693
3 2.0283907 0.2641950 0.6423299 0.5709599 0.4995900 0.4282200
4 3.0094789 0.2151093 0.4730658 0.4205029 0.3679401 0.3153772
5 4.0142807 0.1879412 0.3874176 0.3443712 0.3013248 0.2582784
6 5.0125075 0.1669939 0.3367696 0.2993508 0.2619319 0.2245131
We could use switch
library(shiny)
ui <- fluidPage(
checkboxGroupInput("variable", "Select IEC Classes for TI",c("A Plus" = "ap","A" = "a","B" = "b","C"="c"),
selected = c("A Plus" = "ap")),
plotOutput("plotmeanTI",width = "100%")
)
server <- function(input, output, session){
output$plotmeanTI <- renderPlot({
f1 <- function(nm1){
switch(nm1,
ap = lines(TI_plot[[1]],TI_plot$NTM_A_Plus_mean,col=6),
a = lines(TI_plot[[1]],TI_plot$NTM_A_mean,col=2),
b = lines(TI_plot[[1]],TI_plot$NTM_B_mean,col=3),
c = lines(TI_plot[[1]],TI_plot$NTM_C_mean,col=4)
)
}
if(is.null(input$variable)) {
plot(TI_plot[[1]], TI_plot[[2]],t='o',ylim=c(0,1),xaxs="i",
xlab="Mean Wind Speed", ylab="<TI>")
} else {
plot(TI_plot[[1]], TI_plot[[2]],t='o',ylim=c(0,1),xaxs="i",
xlab="Mean Wind Speed", ylab="<TI>")
f1(input$variable)
}
})
}
shinyApp(ui=ui,server=server)
-output
Using ggplot2
library(shiny)
library(ggplot2)
library(tidyr)
library(dplyr)
ui <- fluidPage(
checkboxGroupInput("variable", "Select IEC Classes for TI",c("A Plus" = "ap","A" = "a","B" = "b","C"="c"),
selected = c("A Plus" = "ap")),
plotOutput("plotmeanTI",width = "100%") )
server <- function(input, output, session){
output$plotmeanTI <- renderPlot({
keyvaldata <- data.frame(key = c('NTM_A_Plus_mean', 'NTM_A_mean', 'NTM_B_mean', 'NTM_C_mean' ),
Var = c('ap', 'a', 'b', 'c'), stringsAsFactors = FALSE)
p1 <- gather(TI_plot, key, val, -MeanWindSpeed_mean, -TurbInt_mean) %>%
left_join(., keyvaldata) %>%
filter(Var %in% input$variable) %>%
ggplot(., aes(MeanWindSpeed_mean, TurbInt_mean, colour = Var)) +
geom_line() +
geom_line(aes(y =val)) +
labs(x = "Mean Wind Speed", y = "<TI>") +
theme_bw()
if(is.null(input$variable)) {
ggplot(TI_plot, aes(MeanWindSpeed_mean, TurbInt_mean)) +
geom_line() +
labs(x = "Mean Wind Speed", y = "<TI>") +
theme_bw()
} else {
p1
}
})
}
shinyApp(ui=ui,server=server)
-output

Resources