I have a shiny app that pulls in NBA statistics from a database and makes a scatterplot. The app.R file code is below. You need to install nbaplotR from github devtools::install_github("abresler/nbastatR") along with nbaplotR if (!require("pak")) install.packages("pak") pak::pak("mrcaseb/nbaplotR"). This app works when I run it locally but not on shinyapps.io when I try to deploy it. In shinyapps.io neither the plot or the table show up. I think the shinyapps.io server is not properly connecting with or installing the above mentioned packages. Any help would be greatly appreciated!
library(devtools)
library(shiny)
library(ggplot2)
library(nbastatR)
library(tidyverse)
library(nbaplotR)
library(nbapalettes)
library(forcats)
library(ggpubr)
library(DT)
library(ggpath)
ui <- fluidPage(
titlePanel("NBA team stats"),
sidebarLayout(
sidebarPanel(
selectInput("x", "X-axis stat",
choices = c("gp", "pctWins", "fgm", "fga", "pctFG",
"fg3m", "fg3a", "pctFG3", "pctFT",
"gpRank", "pctWinsRank", "minutesRank", "fgmRank",
"fgaRank", "pctFGRank", "fg3mRank", "fg3aRank",
"pctFG3Rank", "pctFTRank", "fg2m", "fg2a",
"pctFG2", "wins", "losses", "minutes", "ftm",
"fta", "oreb", "dreb", "treb", "ast", "tov", "stl",
"blk", "blka", "pf", "pfd", "pts", "plusminus",
"winsRank", "lossesRank", "rankFTM", "rankFTA",
"orebRank", "drebRank", "trebRank", "astRank",
"tovRank", "stlRank", "blkRank", "blkaRank", "pfRank",
"pfdRank", "ptsRank", "plusminusRank", "Name_abbreviation"),
selected = "fgm",
multiple = FALSE
),
selectInput("y", "Y-axis stat",
choices = c("gp", "pctWins", "fgm", "fga", "pctFG",
"fg3m", "fg3a", "pctFG3", "pctFT",
"gpRank", "pctWinsRank", "minutesRank", "fgmRank",
"fgaRank", "pctFGRank", "fg3mRank", "fg3aRank",
"pctFG3Rank", "pctFTRank", "fg2m", "fg2a",
"pctFG2", "wins", "losses", "minutes", "ftm",
"fta", "oreb", "dreb", "treb", "ast", "tov", "stl",
"blk", "blka", "pf", "pfd", "pts", "plusminus",
"winsRank", "lossesRank", "rankFTM", "rankFTA",
"orebRank", "drebRank", "trebRank", "astRank",
"tovRank", "stlRank", "blkRank", "blkaRank", "pfRank",
"pfdRank", "ptsRank", "plusminusRank"),
selected = "pctFG",
multiple = FALSE
),
),
mainPanel(
plotOutput("logoscatter"),
DT::DTOutput("Table")
)
)
)
server <- function(input, output) {
#Getting team logos for the plots
Names_abbrev <- valid_team_names()
Names_abbrev[2] <- Names_abbrev[3]
Names_abbrev[3] <- "BKN"
Names_abbrev[26] <- "SAC"
Names_abbrev[27] <- "SA"
Sys.setenv(VROOM_CONNECTION_SIZE=500072)
team_stats_general <- unique(nbastatR::teams_players_stats(seasons = 2023,
types = "team",
tables = "general"))
team_stats_df <- as.data.frame(team_stats_general[[7]])
team_stats_df$Name_abbreviation <- Names_abbrev
team_stats_df$Name_abbreviation <- as.factor(team_stats_df$Name_abbreviation)
team_stats_df <- team_stats_df[,c(10, 12:ncol(team_stats_df))]
output$logoscatter <- renderPlot({
req(input$x, input$y)
plot_scale_x <- if (input$x %in% c("pctWins", "pctFG", "pctFG3", "pctFT", "pctFG2")){
scale_x_continuous(labels = scales::percent_format(accuracy = 1))
}else{
scale_x_continuous()
}
plot_scale_y <- if (input$y %in% c("pctWins", "pctFG", "pctFG3", "pctFT", "pctFG2")){
scale_y_continuous(labels = scales::percent_format(accuracy = 1))
}else{
scale_y_continuous()
}
p1 <- ggplot(data = team_stats_df)+
geom_smooth(aes_string(x = input$x, y = input$y),
method = "lm", se = F, color = "black", linetype = "dashed")+
geom_nba_logos(aes_string(x = input$x, y = input$y, team_abbr = "Name_abbreviation"),
width = 0.075, height = 0.075)+
stat_cor(aes_string(x = input$x, y = input$y, label="..rr.label.."),
label.x.npc = 0.85, label.y.npc = 0.02, size = 6)+
plot_scale_x+
plot_scale_y+
ylab(input$y)+
xlab(input$x)+
theme_bw()+
theme(plot.title = element_text(hjust = 0.5),
text = element_text(size = 18))
p1
})
output$Table <- renderDT({
team_stats_df
})
}
shinyApp(ui = ui, server = server)
Related
I am attempting to build my first shiny app. I need to include multiple graphics (about 50) and I am having problems selecting them based on their label from the dropdown control. I am able to show the first one but I don't know how to display the other ones on the main panel. I currently have 3 on the dropdown control but only the first one works. How do I make lambda2, lambda3 and so on show on the main panel? I also would like to dynamically plot the number of years selected on the slider. Here is the code:
library(shiny)
library(tidyverse)
library(shinythemes)
library(plotly)
library(scales)
library(shinyWidgets)
library(shinydashboard)
# Define input choices
type <- c("lambda","lambda2","lambda3")
table <- structure(list(year = 1991:2010,
lambda = c(0.68854, 0.75545,
1.63359, 1.22282, 1.70744, 1.09692, 0.51159, 1.3904, 1.09132,
0.59846, 0.43055, 0.80135, 0.69027, 0.65646, 0.95485, 1.04818,
0.67859, 1.00461, 1.16665, 1.28203)), row.names = c(NA, -20L), class = "data.frame")
# Define UI
ui <- fluidPage(
navbarPage("Fish",
windowTitle = "Fish Graphs",
sidebarPanel(
h3("Select Graphics to Visualize"),
selectInput(inputId = "graphtype",
label = "Graphic",
choices = type,
selected = "lambda"),
sliderInput(inputId = "Yearslider",
label="Years to plot",
sep="",
min=1991,
max=2011,
value=c(1991,2011))),
mainPanel(plotOutput("plot"))))
####################################
server<- function (input, output, session) {
session$onSessionEnded(function() {
stopApp()
})
output$plot <- renderPlot({
xlabels <- 1991:2011
ggplot(table,aes(year,lamda)) + geom_line(size=1.5,colour="blue") + geom_point(colour="orange",size=4) +
scale_x_continuous("",breaks = xlabels) +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
labs(x="",y=expression("Lambda ("~lambda *")"),title="Population growth rate - fraction per year- \nof Delta Smelt")
if (input$lambda2 == TRUE) {
xlabels <- 1991:2011
ggplot(table,aes(year,lamda)) + geom_line(size=1.5,colour="green") + geom_point(colour="orange",size=4) +
scale_x_continuous("",breaks = xlabels) +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
labs(x="",y=expression("Lambda ("~lambda *")"),title="Population growth rate - fraction per year- \nof Delta Smelt")
}
if (input$lambda3 == TRUE) {
xlabels <- 1991:2011
ggplot(table,aes(year,lamda)) + geom_line(size=1.5,colour="red") + geom_point(colour="orange",size=4) +
scale_x_continuous("",breaks = xlabels) +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
labs(x="",y=expression("Lambda ("~lambda *")"),title="Population growth rate - fraction per year- \nof Delta Smelt")
}
})
}
shinyApp(ui = ui, server = server)
The main issue with your code is that the element of the input list containing the lambda choice is called graphtype. Using input$lambda2 returns NULL. Do e.g. input$graphtype == "lambda2" instead. Also, if you want to switch between different choices you have to use an if-else with a branch for "each" choice or perhaps use switch as I do below. To make your plot react to the year slider I use an reactive which filters the data for years in the selected range. Also, instead of duplicating the ggplot code I would suggest to move it in a separate function outside of the server which also makes it easier to debug the code.
plot_fun <- function(.data, point.color = "black") {
breaks <- unique(.data$year)
ggplot(.data, aes(year, lambda)) +
geom_line(size = 1.5, colour = "blue") +
geom_point(colour = point.color, size = 4) +
scale_x_continuous("", breaks = breaks) +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
labs(x = "", y = expression("Lambda (" ~ lambda * ")"), title = "Population growth rate - fraction per year- \nof Delta Smelt")
}
server <- function(input, output, session) {
session$onSessionEnded(function() {
stopApp()
})
plot_data <- reactive({
table[table$year >= input$Yearslider[1] & table$year <= input$Yearslider[2], ]
})
output$plot <- renderPlot({
switch(input$graphtype,
"lambda" = plot_fun(plot_data(), point.color = "orange"),
"lambda2" = plot_fun(plot_data(), point.color = "purple"),
"lambda3" = plot_fun(plot_data(), point.color = "green")
)
})
}
shinyApp(ui = ui, server = server)
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))
})
}
EDITED to include full UI and sample data
I did read the other StackOverflow qs on this issue, but none seemed to address the cause of my error.
When the app loads, I get "error object [name of district I've selected] not found" for the District (inputID = "d"). I know it must be an issue with the subsetting reactive in the server, but I've tried everything (loading the data in the server, removing the vector from the filter function, changing the data type of the variables).
I also took this code from another Shiny App I built, which works. I can't see any differences between the two, besides that one is geom_point() and this is geom_col() so again, not sure what is going on.
Thanks!
Sample data:
sample <- sample_n(pop, 10)
dput(sample)
structure(list(GazID = c(NA, NA, "13872", NA, "13610", "13985",
"13984", "13434", "13428", "13631"), Province = c("Niolandskaia",
"Kaluzhskaia", "Iaroslavskaia", "Vyborgskaia", "Moskovskaia",
"Volynskaia", "Volynskaia", "Orenburgskaia", "Orenburgskaia",
"Arkhangel'skaia"), District = c(NA, "Suhinichinbezuezdniigorod",
"Romanov", NA, "Zvenigorod", "Kovel", "Lutsk", "Ufa", "Orenburg",
"Mezen"), TotalPop = c(NA, NA, 104104, NA, 71746, 103381, 102779,
93145, 62740, 26796), Male = c(NA, NA, 48604, NA, 36948, 52266,
50393, 46403, 32617, 13078), Female = c(NA, NA, 55500, NA, 34798,
51115, 52386, 46742, 30123, 13718), City = c(NA, 5552, NA, NA,
1253, 4254, 5552, 6682, 9533, NA), Rural = c(NA, NA, NA, NA,
70493, 99127, 97228, 86483, 53207, NA)), row.names = c(NA, -10L
), class = c("tbl_df", "tbl", "data.frame"))
Above the UI:
library(tidyverse)
library(readr)
library(shiny)
library(stringr)
library(rebus)
pop <- read_csv("pop.csv")
pop$TotalPop <- str_replace_all(pop$TotalPop, pattern = fixed(","), replacement = "")
pop$Male <- str_replace_all(pop$Male, pattern = fixed(","), replacement = "")
pop$Female <- str_replace_all(pop$Female, pattern = fixed(","), replacement = "")
pop$City <- str_replace_all(pop$City, pattern = fixed(","), replacement = "")
pop$Rural <- str_replace_all(pop$Rural, pattern = fixed(","), replacement = "")
pop$District <- str_remove_all(pop$District, pattern = "[^[:alnum:]]")
pop$TotalPop <- as.numeric(pop$TotalPop)
pop$Male <- as.numeric(pop$Male)
pop$Female <- as.numeric(pop$Female)
pop$City <- as.numeric(pop$City)
pop$Rural <- as.numeric(pop$Rural)
pop$GazID <- as.character(pop$GazID)
pop$District <- str_trim(pop$District)
The UI:
ui <- fluidPage(
titlePanel("Population Data from VSO"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "y", #internal label
label = "Population to map", #label that user sees
choices = c("Total population" = "TotalPop",
"Male population" = "Male",
"Female population" = "Female",
"Urban population" = "City",
"Rural population" = "Rural"),
selected = "TotalPop"),
selectizeInput(inputId = "d",
label = "Select district",
choices = c(pop$District),
multiple = TRUE, # can choose multiple
options = list(maxItems = 5))),
mainPanel(
plotOutput("plot")
)
)
)
The server:
server <- function(input, output) {
pop_subset <- reactive({
req(input$d)
filter(pop, District %in% c(input$d)
)})
output$plot <- renderPlot({
ggplot(data = pop_subset(), aes_string(x = pop_subset()$District, y = input$y)) +
geom_col(aes(fill = pop_subset()$District)) +
labs(x = "District", y = "Population") +
scale_fill_discrete(name = "Districts")
})}
shinyApp(ui = ui, server = server)
The problem is that you are using aes_string in your ggplot, but trying to pass District without quotes. I realize you need aes_string because you are using input$y, so just change your plot call to
output$plot <- renderPlot({
req(pop_subset())
ggplot(data = pop_subset(), aes_string(x = "District", y = input$y)) +
geom_col(aes(fill = District)) +
labs(x = "District", y = "Population") +
scale_fill_discrete(name = "Districts")
})
For reproducibility, packages and some sample data (no idea of its true representative nature, doesn't really matter I think).
library(dplyr)
library(shiny)
library(ggplot2)
set.seed(42)
n <- 50
pop <- data_frame(
TotalPop = sample(1e4, size=n, replace=TRUE)
) %>%
mutate(
Male = pmax(0, TotalPop - sample(1e4, size=n, replace=TRUE)),
Female = TotalPop - Male,
City = sample(LETTERS, size=n, replace=TRUE),
District = sample(letters, size=n, replace=TRUE)
)
I' trying to modify pch parameter of plot by inserting an input from selectInput:
selectInput("points", "Points:",
list("Job lost" = "joblost",
"Sex" = "sex",
))
into
output$Plot <- renderPlot({
plot(as.formula(formula()),data=Benefits,
main = caption(), pch = as.numeric(input$points),
col=as.numeric(input$points))
})
Unfortunately, I get an error: cannot coerce type 'closure' to vector of type 'double'. What steps should I take to fix this ? Of course, both joblost and sex are factors.
Full code:
library(shiny)
library(Ecdat)
attach(Benefits)
u <- shinyUI(pageWithSidebar(
headerPanel("Social benefits"),
sidebarPanel(
selectInput("variable1", "Zmienna X:",
list("Bezrobocie" = "stateur",
"Max zasilek" = "statemb",
"Wiek" = "age",
"Staz w bezrobociu" = "tenure",
"Replacement rate" = "rr"
)),
selectInput("variable2", "Zmienna Y:",
list("Bezrobocie" = "stateur",
"Max zasilek" = "statemb",
"Wiek" = "age",
"Staz w bezrobociu" = "tenure",
"Replacement rate" = "rr"
)),
selectInput("points", "Punkty:",
list("Powod utraty pracy" = "joblost",
"Plec" = "sex",
"Nie-bialy" = "nwhite",
">12 lat szkoly" = "school12",
"Robotnik fizyczny" = "bluecol",
"Mieszka w miescie" = "smsa",
"Zonaty" = "married",
"Ma dzieci" = "dkids",
"Male dzieci" = "dykids",
"Glowa rodziny" = "head",
"Otrzymuje zasilki" = "ui"
)),
checkboxInput("reg", "Pokaz krzywa regresji", FALSE)
),
mainPanel(
plotOutput("Plot")
)
))
s <- shinyServer(function(input, output)
{
formula <- reactive({paste(input$variable2,"~",input$variable1)})
caption <- renderText({formula()})
pkt <- reactive({input$points})
#pkt <- renderText({paste(input$points)})
output$Plot <- renderPlot({
plot(as.formula(formula()),data=Benefits,
main = caption(), pch = as.numeric(input$points),
col=as.numeric(input$points))
if(input$reg == TRUE){
abline(lm(as.formula(formula())),col ="red", lwd = 2)
legend("topleft",inset = 0.02, legend = "Krzywa regresji",
col="red",lty = 1, lwd = 2)
}
})
})
shinyApp(u,s)
The issue was resolved by using a switch in selectInput:
pkt <- reactive({
switch(input$points,
"Powod utraty pracy" = joblost,
"Plec" = sex,
"Nie-bialy" = nwhite,
">12 lat szkoly" = school12,
"Robotnik fizyczny" = bluecol,
"Mieszka w miescie" = smsa,
"Zonaty" = married,
"Ma dzieci" = dkids,
"Male dzieci" = dykids,
"Glowa rodziny" = head,
"Otrzymuje zasilki" = ui)
})
txt <- renderText({paste(input$points)})
output$Plot <- renderPlot({
plot(as.formula(formula()),data=Benefits,
main = caption(), pch = as.numeric(pkt()),
col=as.numeric(pkt()))
I'm currently having issues rendering my plot in shiny. The layout is all fine, but when run the plot does not appear.
Link to data in csv file:
https://www.dropbox.com/s/hv3k12ja9r10tzz/pointvaluedfmelt.csv?dl=0
UI Code:
library(shiny)
library(ggplot2)
library(RColorBrewer)
pointvaluedf.melt<- read.csv("pointvaluedfmelt.csv", stringsAsFactors = F)
pointvaluedf.melt$X<- NULL
pointvaluedf.melt$PLAYER_NAME<- as.factor(pointvaluedf.melt$PLAYER_NAME)
pointvaluedf.melt$TEAM_ABBREVIATION<- as.factor(pointvaluedf.melt$TEAM_ABBREVIATION)
pointvaluedf.melt$name.zone<- as.factor(pointvaluedf.melt$name.zone)
ui <- fluidPage(
titlePanel("Top 5 Most Valuable Shots by Player"),
sidebarLayout(
sidebarPanel(selectInput("team",
label = "Choose a Team",
choices = c("Celtics", "Nets","Knicks", "76ers", "Raptors",
"Mavericks","Rockets","Grizzlies","Pelicans",
"Spurs","Bulls","Cavs","Pistons","Pacers","Bucks",
"Nuggets","Timberwolves","Thunder","Blazers",
"Jazz","Hawks","Hornets","Heat","Magic","Wiz",
"Warriors","Clippers","Lakers","Suns","Kings"),
selected = "Celtics"), width = 2
),
mainPanel(plotOutput("myplot"))
))
Server Code:
library(shiny)
library(ggplot2)
library(RColorBrewer)
pointvaluedf.melt<- read.csv("pointvaluedfmelt.csv", stringsAsFactors = F)
pointvaluedf.melt$X<- NULL
pointvaluedf.melt$PLAYER_NAME<- as.factor(pointvaluedf.melt$PLAYER_NAME)
pointvaluedf.melt$TEAM_ABBREVIATION<- as.factor(pointvaluedf.melt$TEAM_ABBREVIATION)
pointvaluedf.melt$name.zone<- as.factor(pointvaluedf.melt$name.zone)
server <- function(input, output) {
df<- reactive({pointvaluedf.melt[pointvaluedf.melt$TEAM_ABBREVIATION==input$team,]})
output$myplot <- renderPlot(function(){
dd<- df()
tea <- switch(input$team,
"Celtics" = "BOS",
"Nets" = "BKN",
"Knicks" = "NYK",
"76ers" = "PHI",
"Raptors" = "TOR",
"Mavericks" = "DAL",
"Rockets" = "HOU",
"Grizzlies" = "MEM",
"Pelicans" = "NOP",
"Spurs" = "SAS",
"Bulls" = "CHI",
"Cavs" = "CLE",
"Pistons" = "DET",
"Pacers" = "IND",
"Bucks" = "MIL",
"Nuggets" = "DEN",
"Timberwolves" = "MIN",
"Thunder" = "OKC",
"Blazers" = "POR",
"Jazz" = "UTA",
"Hawks" = "ATL",
"Hornets" = "CHA",
"Heat" = "MIA",
"Magic" = "ORL",
"Wiz" = "WAS",
"Warriors" = "GSW",
"Lakers" = "LAL",
"Clippers" = "LAC",
"Suns" = "PHX",
"Kings" = "SAC")
p<- ggplot(data=head(subset(dd, TEAM_ABBREVIATION %in% tea)
[order(-subset(dd, TEAM_ABBREVIATION %in% tea)[,4]),],5),
aes(x=reorder(name.zone,-value), y=value))+
geom_bar(stat="identity", fill="#4292C6", col="black", size=1.2)+
theme(axis.text.x=element_text(angle=35, hjust=1))+
labs(x="Player and Shot Type", y="Point Value", title="Top 5 Value Shots")
print(p)
})
}
There are some errors in there:
1- Render plot does not need the "function()" keyword on it, just renderPlot({})
2- You are not using reactive the proper way. You can make it simple and better with two reactive objects, and renderPlot consuming it besides put everything inside the renderPlot logic. This way, you can reuse objects and make your code cleaner.
3- Because you are doing reactive the wrong way, the data.frame was empty when you change the values...
library(shiny)
library(ggplot2)
library(RColorBrewer)
pointvaluedf.melt<- read.csv("pointvaluedfmelt.csv", stringsAsFactors = F)
pointvaluedf.melt$X<- NULL
pointvaluedf.melt$PLAYER_NAME<- as.factor(pointvaluedf.melt$PLAYER_NAME)
pointvaluedf.melt$TEAM_ABBREVIATION<- pointvaluedf.melt$TEAM_ABBREVIATION
pointvaluedf.melt$name.zone<- as.factor(pointvaluedf.melt$name.zone)
ui <- fluidPage(
titlePanel("Top 5 Most Valuable Shots by Player"),
sidebarLayout(
sidebarPanel(selectInput("team",
label = "Choose a Team",
choices = c("Celtics", "Nets","Knicks", "76ers", "Raptors",
"Mavericks","Rockets","Grizzlies","Pelicans",
"Spurs","Bulls","Cavs","Pistons","Pacers","Bucks",
"Nuggets","Timberwolves","Thunder","Blazers",
"Jazz","Hawks","Hornets","Heat","Magic","Wiz",
"Warriors","Clippers","Lakers","Suns","Kings"),
selected = "Celtics"), width = 2
),
mainPanel(plotOutput("myplot"))
))
server <- function(input, output, session) {
df <- reactive({
pointvaluedf.melt[pointvaluedf.melt$TEAM_ABBREVIATION==tea(),]
})
tea <- reactive({
switch(input$team,
"Celtics" = "BOS",
"Nets" = "BKN",
"Knicks" = "NYK",
"76ers" = "PHI",
"Raptors" = "TOR",
"Mavericks" = "DAL",
"Rockets" = "HOU",
"Grizzlies" = "MEM",
"Pelicans" = "NOP",
"Spurs" = "SAS",
"Bulls" = "CHI",
"Cavs" = "CLE",
"Pistons" = "DET",
"Pacers" = "IND",
"Bucks" = "MIL",
"Nuggets" = "DEN",
"Timberwolves" = "MIN",
"Thunder" = "OKC",
"Blazers" = "POR",
"Jazz" = "UTA",
"Hawks" = "ATL",
"Hornets" = "CHA",
"Heat" = "MIA",
"Magic" = "ORL",
"Wiz" = "WAS",
"Warriors" = "GSW",
"Lakers" = "LAL",
"Clippers" = "LAC",
"Suns" = "PHX",
"Kings" = "SAC")
})
output$myplot <- renderPlot({
p <- ggplot(data=head(subset(df(), TEAM_ABBREVIATION %in% tea())
[order(-subset(df(), TEAM_ABBREVIATION %in% tea())[,4]),],5),
aes(x=reorder(name.zone,-value), y=value))+
geom_bar(stat="identity", fill="#4292C6", col="black", size=1.2)+
theme(axis.text.x=element_text(angle=35, hjust=1))+
labs(x="Player and Shot Type", y="Point Value", title="Top 5 Value Shots")
p
})
}
shinyApp(ui, server)