R Flexdashboard, how to get map to show in dashboard? - r-markdown

library(flexdashboard)
library(tidycensus)
library(tidyverse)
library(mapview)
library(dplyr)
library(tigris)
library(leafsync)
library(leafpop)
library(readxl)
library(DT)
library(highcharter)
{r}
#Importing Data ****Update file path before running****
states=data.frame(read_excel('C:/Users/pmckercher/Documents/CISA Research/CISA Funding Data.xlsx',
sheet = 'Funding By State',col_names = TRUE ))
us_geo=tigris::states(cb=FALSE, resolution = '20m') #State Sahpe File Download
all_data=inner_join(us_geo,states, by=c("NAME"="State")) #Joinging the two datasets
# These are shells, replace zcol= '' with a percentage of use column (will have to
#update the python file to calculate this when we get the real data) to make the display
#show how much of each states allocation has been provided.
Map22=mapview(all_data,zcol=c('fund_22'),col.regions = RColorBrewer::brewer.pal(11, "RdYlGn"), alpha.regions = 1, popup= popupTable(all_data,zcol=c('NAME', 'fund_22','fund_23','fund_24','fund_25')), label=c('NAME'))
Map22
This produces this visualization in the viewer:
Mapview Interactive Map
But, when the Dashaboard window pops up. it produces this where the map should be:
Buffering bars
How do I get the Interactive map to show up in the Dashboard window?

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]]

rPivotTable in Shiny showing black areas outside of pivot when scrolled

I an using rpivotTable in a Shiny app
in UI it is inside a tabSetPanel:
tabPanel("Pivot Table",
shinycssloaders::withSpinner(
rpivotTableOutput("pivot_table")
)
)
in Server it is updated once the dataframe is loaded and filtered:
output$pivot_table <- renderRpivotTable({
rpivotTable(data = filtered_df(), rows=c("HIGH_LEVEL_GROUP_TERM", "HIGH_LEVEL_TERM", "AE_AS_PREFERRED_TERM"),
vals = "SAPPHIRE_CASE_ID_VERSION", aggregatorName = "Count Unique Values", rendererName = "Heatmap", width="100%")
})
When I scroll down the page, anything not observable immediately seems to have black on the outside of the pivot table?
I am using "shinydashboard"....

Is there a way to have previous/next links at the bottom of shiny presentations?

I am working in RStudio and creating a markdown Shiny presentation (which I believe uses IOslides).
Currently the generated presentation doesn't have any navigational help, the user has to know they need to use left/right arrows to move to the next or previous slides. Even when deployed to server I don't see any arrows at the bottom of presentations.
I have searched through documentation and here to see if this is possible, but can't seem to find anything.
Is there some setting to include a Previous/Next type link at the bottom of every slide?
Process to create my presentation in R Studio:
New file > R Markdown > Shiny > Shiny presentation
The issue occurs even with the sample code when creating a new file - there are no navigation arrows
Published example (where there are no navigation arrows):
https://regolith.shinyapps.io/test
And the sample code (as generated by R studio):
---
title: "test"
author: ""
date: "24 January 2017"
output: ioslides_presentation
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Shiny Presentation
This R Markdown presentation is made interactive using Shiny. The viewers of the presentation can change the assumptions underlying what's presented and see the results immediately.
To learn more, see [Interactive Documents](http://rmarkdown.rstudio.com/authoring_shiny.html).
## Interactive Plot
```{r eruptions}
inputPanel(
selectInput("n_breaks", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 20),
sliderInput("bw_adjust", label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
renderPlot({
hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
xlab = "Duration (minutes)", main = "Geyser eruption duration")
dens <- density(faithful$eruptions, adjust = input$bw_adjust)
lines(dens, col = "blue")
})
```
## Bullets
- Bullet 1
- Bullet 2
- Bullet 3
## R Output
```{r cars}
summary(cars)
```

Click on marker to open plot / data table

I'm working on leaflet with shiny. The tools is basic, i have a map with some markers (coming from a table with LONG and LAT).
What I want to do is to open a table or a graph when i click on the marker.
Is there a simple way to do it?
Do you have a really simple example: you have a maker on a map, you click on the marker, and there is a plot or a table or jpeg that s opening?
Here is another example, taken from here and a little bit adapted. When you click on a marker, the table below will change accordingly.
Apart from that, a good resource is this manual here:
https://rstudio.github.io/leaflet/shiny.html
library(leaflet)
library(shiny)
myData <- data.frame(
lat = c(54.406486, 53.406486),
lng = c(-2.925284, -1.925284),
id = c(1,2)
)
ui <- fluidPage(
leafletOutput("map"),
p(),
tableOutput("myTable")
)
server <- shinyServer(function(input, output) {
data <- reactiveValues(clickedMarker=NULL)
# produce the basic leaflet map with single marker
output$map <- renderLeaflet(
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addCircleMarkers(lat = myData$lat, lng = myData$lng, layerId = myData$id)
)
# observe the marker click info and print to console when it is changed.
observeEvent(input$map_marker_click,{
print("observed map_marker_click")
data$clickedMarker <- input$map_marker_click
print(data$clickedMarker)
output$myTable <- renderTable({
return(
subset(myData,id == data$clickedMarker$id)
)
})
})
})
shinyApp(ui, server)
There is a leaflet example file here:
https://github.com/rstudio/shiny-examples/blob/ca20e6b3a6be9d5e75cfb2fcba12dd02384d49e3/063-superzip-example/server.R
# When map is clicked, show a popup with city info
observe({
leafletProxy("map") %>% clearPopups()
event <- input$map_shape_click
if (is.null(event))
return()
isolate({
showZipcodePopup(event$id, event$lat, event$lng)
})
})
Online demo (see what happens when you click on a bubble):
http://shiny.rstudio.com/gallery/superzip-example.html
On the client side, whenever a click on a marker takes place, JavaScript takes this event and communicates with the Shiny server-side which can handle it as input$map_shape_click.

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!