Rendering in Shiny: red error before reactive data loads - shiny

I am sure there is a function out there that will let me wait to render my Echarts4R output once my pickers & reactive data have loaded, as to mitigate the ugly red warning until they do! Once the reactive data is loaded, I get a nice output as such. It would be even better to have a little loading symbol or something while they load. It only takes about a second to load, though, so that isnt imperative.
Here are some example code snippets.
The UI for the graphic:
box(width = 12, title = "Total Escalated Project Costs by Calendar Year", solidHeader = TRUE, collapsible = TRUE, status = "primary"
,echarts4rOutput("initiative_cashflow")
And the server for the graphic:
output$Breakdown_by_Project <- renderEcharts4r({
breakdown_by_project_data <- init_data() %>%
group_by(Project) %>%
summarise(total_project_cost = sum(`Escalated Project Cost`))%>%
select(Project, total_project_cost)%>%
e_charts(Project)%>%
e_pie(total_project_cost, radius = c("50%", "70%"))%>%
e_legend(show = FALSE) %>%
e_tooltip()})
Any help would be appreciated!
Thanks!

Related

How to update fillColor palette to selected input in shiny map?

I am having trouble transitioning my map from static to reactive so a user can select what data they want to look at. Somehow I'm not successfully connecting the input to the dataframe. My data is from a shapefile and looks roughly like this:
NAME Average Rate geometry
1 Alcona 119.7504 0.1421498 MULTIPOLYGON (((-83.88711 4...
2 Alger 120.9212 0.1204398 MULTIPOLYGON (((-87.11602 4...
3 Allegan 128.4523 0.1167062 MULTIPOLYGON (((-85.54342 4...
4 Alpena 114.1528 0.1410852 MULTIPOLYGON (((-83.3434 44...
5 Antrim 124.8554 0.1350004 MULTIPOLYGON (((-84.84877 4...
6 Arenac 127.8809 0.1413534 MULTIPOLYGON (((-83.7555 43...
In the server section below, you can see that I tried to use reactive to get the selected variable and when I write print(select) it does print the correct variable name, but when I try to put it into the colorNumeric() function it's clearly not being recognized. The map I get is all just the same shade of blue instead of different shades based on the value of the variable in that county.
ui <- fluidPage(
fluidRow(
selectInput(inputId="var",
label="Select variable",
choices=list("Average"="Average",
"Rate"="Rate"),
selected=1)
),
fluidRow(
leafletOutput("map")
)
)
server <- function(input, output, session) {
# Data sources
counties <- st_read("EITC_counties.shp") %>%
st_transform(crs="+init=epsg:4326")
counties_clean <- select(counties, NAME, X2020_Avg., X2020_Takeu)
counties_clean <- counties_clean %>%
rename("Average"="X2020_Avg.",
"Rate"="X2020_Takeu")
# Map
variable <- reactive({
input$var
})
output$map <- renderLeaflet({
select <- variable()
print(select)
pal <- colorNumeric(palette = "Blues", domain = counties_clean$select, na.color = "black")
color_pal <- counties_clean$select
leaflet()%>%
setView( -84.51, 44.18, zoom=5) %>%
addPolygons(data=counties_clean, layerId=~NAME,
weight = 1, smoothFactor=.5,
fillOpacity=.7,
fillColor=~pal(color_pal()),
highlightOptions = highlightOptions(color = "white",
weight = 2,
bringToFront = TRUE)) %>%
addProviderTiles(providers$CartoDB.Positron)
})
}
shinyApp(ui, server)
I've tried making the reaction into an event and also using the observe function using a leaflet proxy but it only produced errors. I also tried to skip the reactive definition and just put input$var directly into the palette (counties_clean$input$var), but it similarly did not show any color variation.
When I previously created a static map setting the palette using counties_clean$Average it came out correctly, but replacing Average with a user input is where I appear to be going wrong. Thanks in advance for any guidance you can provide and please let me know if I can share any additional clarification.
Unfortunately, your code is not reproducible without the data, but the mistake is most likely in this line
color_pal <- counties_clean$select
What this line does, is to extract a column named select from your data. This column is not existing, so it will return NULL.
What you want though, is to extract a column whose name is given by the content of select, so you want to try:
color_pal <- counties_clean[[select]]

Using leaflet for R to make a pie chart with GIS data

I am trying to make a point map that replaces the points with pie charts to make the information quicker to understand for the layman.
the alternative is:
"text": statistic
"text": statistic
"text": statistic
"text": statistic
library(shiny)
library(shinydashboard)
library(tidyverse)
library(shinyWidgets)
library(plotly)
library(leaflet)
library(scales)
library(sp)
library(sf)
library(ggplot2)
library(leaflet.minicharts)
ui <- dashboardPage( skin = "purple",
dashboardHeader(title = "Practice Map", titleWidth = 400),
dashboardSidebar(disable = TRUE),
dashboardBody(
fluidPage(
useShinydashboard(),
fluidRow(
leafletOutput(outputId = "map")
)
)))
server <- function(input, output) {
output$map <- renderLeaflet ({
#extracting coordinates and adding to data
map.tb <- map%>%
st_coordinates() %>%
as_tibble() %>%
rename(lon = 1, lat = 2) %>%
bind_cols(map %>% st_drop_geometry())
l <- leaflet(map) %>%
addTiles() %>%
addMinicharts(
lng = map.tb$lon,
lat = map.tb$lat,
type = pie,
chartdata = map.tb[,c(column1,column2,
column3,column4)],
width = 60 * sqrt(map$colmun1) / sqrt(max(map$column1)), transitionTime = 0,
fillColor = d3.schemeCategory10[1],
colorPalette = d3.schemeCategory10
I keep getting this error.
Error in match.arg: 'arg' must be NULL or a character vector
does this mean I am missing an argument somewhere?
Let me know if any info is missing.
Not really the way you are trying, but did you consider getting this done via QGIS? you can plot nodes on any map rather easily, and then instead of each point marker plot a pie chart with specified attributes.
you would just need to create a .txt file or similar with the following categories:
NODEx NODEy stat1 stat2 stat3 stat4
of course you can also enrich the file with node names or other infos, but this would work. Finally:
-Import the so-created file as delimited text,
-Right click the layer -> Poperties -> Diagram
customize the pie chart the way you want.
I know I went a bit off track, but sometimes there are better tools for facing the same goal :)

How can I get my output to display in a box item with renderUI and switch?

I'm trying to create a dynamic UI. In this case, when a user selects a Program name, the professor box will only display the professor names who teach in that program. Based on the program, the professor ("prof") output should populate.
I've tried renaming things to see if I might have double-named items, but to no avail. When I run the app, the Professor box appears but it gives me no names based on the filtering of the program. No error is generated. I've looked at this for hours and not sure if I'm missing something so simple...
UI
tabItem(tabName = "dashboard",
fluidRow(
selectInput("selectMode",label=h3("Select Mode"),
choices = c("Overall"="Overall")
),
box(width =3, solidHeader = T, background = "blue",
selectInput("selectProgram",label=h3("Select Program"),
choices = list(
"Social Work" = "SWO",
"Nursing" ="NUR"))
),
uiOutput(outputId = 'course'),
uiOutput(outputId = 'prof')))
Server
server <- function(input, output){
var <- reactive({
switch(input$selectProgram, "Nursing" =
unique(
indicators %>% filter(program=="NUR")%>%
select(Professor)),
"Social Work" = unique(indicators %>%
filter(program=="SWO")%>%select(Professor))
)
})
output$prof <- renderUI({
box(width =3, solidHeader = T, background = "blue",
selectInput("reactiveProfessor", "Select Professor", choices =
var())
)
})
I want the Professor box to display names of the appropriate professors based on the program selection.

Shiny: update selectinput on change of inFile

I want to provide inputselect "choices" in dependency of uploaded files (fileInput). In the example below I want as.list(mydata[1, 1:5]) as values for inputselect choices. Later on the subsetting values will be dynamic and is not showed here.
I tried several approaches suggested in the forum (reactive, observe, reactiveValue and their combination) without much success.
My script runs partially, however I need a page refresh to the get the "choices" uploaded and reload the file again.
server.R
shinyServer(function(input, output, session) {
output$contents <- renderDataTable({
inFile <<- input$SoftRecom
if (is.null(inFile))
return(NULL)
filedatapath <<- reactive({inFile$datapath})
mydata <<- read.csv(filedatapath(), header = TRUE, sep = ',')
mydata
})
mychoices <<- reactive({
mydata
print(mydata)
})
output$vg <- renderUI({
selectInput("vg", label = p("goal", style = "color:#FFA500"),
mychoices()[1,1:5], selected = 1)
})
output$vp <- renderUI({
selectInput("procedure", label = p("procedure", style = "color:#FFA500"),
choices = c("proecudures"), selected = 1)
})
output$vm <- renderUI({
selectInput("procedure", label = p("procedure", style = "color:#FFA500"),
choices = c("ChIP-seq"), selected = 1)
})
})
ui.R
shinyUI(fluidPage(theme = "bootstrap.css",
titlePanel("simple software recommendation sytem"),
sidebarLayout(
sidebarPanel(
fileInput('SoftRecom', 'choose dataset'),
uiOutput("vg"), # variable goal
uiOutput("vp"), # variable procedure
uiOutput("vm") # variable method
),
mainPanel(
dataTableOutput('contents')
)
)
))
I have seen many examples and answers in the forum, that are very close (or even match) my question. Sorry for being so obtuse. If someone could point me to the problem, I would be very thankful.
Jay
Eventually I found the solution by myself. Don't get confused by the different server code in my question and the answer. Just look at the relationship between
uiOutput('pipelinestep') and
output$pconst <<- renderUI({selectizeInput(
'pconst', 'construct software workflow', choices = as.character(mysoft[mysoft$goal==mypipefilter, 3]),
multiple = TRUE, options = list(maxItems = 1))}
UI.R
I had to insert: uiOutput("pipelinestep") see line 8
shinyUI(fluidPage(theme = "bootstrap.css",
titlePanel( h2("simple software recommendation system", style = "color:#FFA500")),
sidebarLayout(position = "left",
sidebarPanel(width =3,
# chose standard pipeline
selectInput("selectpipe", "select standard pipeline:", choices = pipechoices),
# software details
*uiOutput("pipelinestep")*, # software per pipeline step,
# construct software workflow based on selected pipeline step
uiOutput("pconst")
))))
server.R
see from line 5 to 7. "Choices" gets new values assigned as soon a change is detected. Please see documentation here: http://shiny.rstudio.com/articles/dynamic-ui.html
pipelinestepsoftInput <<- reactive({
mypipefilter <- input$pipelinestep
softperpipe <<- mysoft[mysoft$goal==mypipefilter ,c(1,3,5:7), drop = FALSE]
## provides software choices related to the pipeline step
output$pconst <<- renderUI({selectizeInput(
'pconst', 'construct software workflow', choices = as.character(mysoft[mysoft$goal==mypipefilter, 3]),
multiple = TRUE, options = list(maxItems = 1))})
## input for outputDataTable
softperpipe
})

Shiny renders a responsive rCharts leaflet map once, but is blank if you change the input variable

I am producing a Shiny App that produces a leaflet (rCharts) map depending on which bus route you pick. Everything renders perfectly at first glimpse, but if you change the route number, an empty map appears (not even a tilelayer). This isn't specific to the route number. For example, I can pick any route number to produce the first plot successfully, whereas the second plot, regardless of route number, is blank.
Has anyone come across this before? Is there a workaround?
Here is a simple example.
ui.R:
library(shiny)
library(rCharts)
shinyUI(fluidPage(
titlePanel("Responsive Leaflet Map using rCharts"),
sidebarLayout(
sidebarPanel( "",
selectInput(
'route', 'Pick a bus route:',
choices = as.character(c("232","229"),
selectize = FALSE)
)
),
mainPanel("",
chartOutput('map', 'leaflet')
)
)
))
server.R:
library(shiny)
library(rCharts)
library(RJSONIO)
library(rgdal)
shinyServer(function(input, output) {
output$map <- renderMap({
filename <- paste('json/',input$route,'.geojson',sep='')
json <- fromJSON(file = filename)
map3 <- Leaflet$new()
map3$tileLayer(provide='Esri.WorldTopoMap')
map3$setView(c(49.2494,-122.9797), zoom = 10)
map3$set(dom = 'map')
map3$fullScreen(TRUE)
map3$geoJson(
json,
style = "#!
{color: '#c93312'}!#")
map3
})
})
Thanks so much for any help you are able to provide.
C
The trick is to remove map3$set(dom = 'map'). Problem solved!