I am creating a flexdashboard and including a leaflet map in it.
Once I added the map to the markdown file when the dashboard renders nothing appears on it, and I get the following warning in the R Markdown console:
Warning in normalizePath(path.expand(path), winslash, mustWork) :
path[1]="figure-html/chart_categories-1.mb.png": The system cannot find the path specified
Warning in normalizePath(path.expand(path), winslash, mustWork) :
path[1]="figure-html/chart_categories-1.png": The system cannot find the path specified
Now, the error is strange as if I run it independently of the dashboard it renders without an issue, it also renders without an issue when I create a new dashboard and the leaflet map is the only chunk but with the rest of my code it causes issues.
Also, if I run the dashboard without evaluating the map chunk it runs perfectly.
Any ideas what could be causing this?
My leaflet code below:
countries <- readOGR("/filepath")
country_map = sqlQuery(pa,"SELECT *
FROM [PortAnalyzer].[dbo].[Country] c
join BarraCountryRegion b on right(b.Factor,3) = c.CountryCode
where b.Model = 'GEM3L' and LEN(b.Factor)=9 ",stringsAsFactors = FALSE)
countries#data = countries#data %>% left_join(country_map,c('ISO_A3' = 'CountryCode'))
country_attribution = data_melt %>% filter(Category == 'Country' & Style =='Total' & variable == 'Total' &
!`Sub-Category` %in% c('Total','CASH'))
countries#data = countries#data %>% left_join(country_attribution,c('Factor' = 'Sub-Category'))
map <- leaflet(countries)
# Create a continuous palette function
pal <- colorNumeric(
palette = "Blues",
domain = countries$value
)
binpal = colorNumeric('RdYlGn',countries$value)
test = countries#data
# Apply the function to provide RGB colors to addPolygons
map %>%
addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,color = binpal(countries$value)
) %>%
addLegend("bottomright", pal = binpal, values = countries$value,
title = "Total Return",
labFormat = labelFormat(suffix = "%"),
opacity = 1
)
I was able to make it work by entering the Leaflet in the Shiny function:
renderLeaflet({})
Related
I created a highchart and hope to pass the point information (name, description etc...) into another function. However I can't seem to find a way to access the point name. Below is my current attempt.
# Generate chart
highchart() %>%
hc_chart(type = 'organization', inverted = TRUE) %>%
hc_title(text = sprintf('%s Org Chart', chartName)) %>%
hc_add_series(
name = chartName,
data = hierarchyList,
nodes = nodeList,
colorByPoint = FALSE,
color = '#D6E8F3',
dataLabels = list(color = 'black',
nodeFormat = getNodeFormat("{point.image}", "{point.name}", "{point.title}", "{point.description}", ...),
borderColor = 'white',
nodeWidth = 190
) %>%
hc_tooltip(outside = TRUE)
}
getNodeFormat <- function(image, name, title, description...) {
... #more codes here
}
In the getNodeFormat function, there are other computations and data accessing that requires the actual name string of the point. However, when I try to print out name in getNodeFormat, it displays "{point.name}" instead of the actual name of the point.
Other attempts instead of "{point.name}" are point.name, and {point.name}. None of them worked and the error stated "object not found".
Is there a way where I can access the point information directly? Any help will be appreciated!
Anyone created a leaflet map in Code Workbook using r-Leaflet? I have a functioning script that runs (also double checked in R) but how do I get it to visualise and then use in a Report etc. I have tried various tweaks on what may get it to run but no success - any ideas
leaflet_map <- function(map_data) {
library(leaflet)
data<-map_data
# first cut the continuous variable into bins
# these bins are now factors
data$Fill_rateLvl <- cut(data$Fill_rate,
c(0,.5,0.6,0.7,0.8,0.9,1), include.lowest = T,
labels = c('<50%', '50-60%', '60-70%', '70-80%', '80-90%','90-100%'))
# then assign a palette to this using colorFactor
# in this case it goes from red for the smaller values to yellow and green
# standard stoplight for bad, good, and best
FillCol <- colorFactor(palette = 'RdYlGn', data$Fill_rateLvl)
m<-leaflet() %>%
addTiles() %>%
addProviderTiles(providers$CartoDB.Positron)%>%
setView(lng = -0, lat = 50, zoom = 8) %>%
addCircleMarkers(data = data, lat = ~lat, lng = ~long,
color = ~FillCol(Fill_rateLvl), popup = data$Lead_employer,
radius = ~sqrt(Fill_rate*50), group = 'Fill rate') %>%
addLegend('bottomright', pal = FillCol, values = data$Fill_rateLvl,
title = 'Fill rate for next two weeks',
opacity = 1)
return(NULL)
}
I am not familiar with R in code workbook, but it sounds to me that you need to materialize your leaflet map as a dataset and then consume it in some sort of map compatible UI.
For example slate has a map widget which is backed by leaflets. You can find documentation and examples for it in https://www.palantir.com/docs/foundry/slate/widgets-map/
I am receiving the following error message when I run leaflet in the knitr program: ## Error in file(con, "rb"): cannot open the connection. There is no error message, however, when I run this program in regular r. I can't figure out what the problem is. Here is the code I am trying to use (I got it from https://www.paulamoraga.com/tutorial-geostatistical-data/#):
library(leaflet)
index <- inla.stack.index(stack = stk.full, tag = "pred")$data
prev_mean <- result$summary.fitted.values[index, "mean"]
raster_prev_mean <- rasterize(x = coop, y = ra, field = prev_mean, fun = mean)
pal <- colorNumeric("viridis", c(0, 1), na.color = "transparent")
leaflet() %>% addProviderTiles(providers$CartoDB.Positron) %>%
addRasterImage(raster_prev_mean, colors = pal, opacity = 0.5) %>%
addLegend("bottomright", pal = pal, values = values(raster_prev_mean), title = "Prevalence") %>%
addScaleBar(position = c("bottomleft"))
Did you install/include the packages from the start of the demo? Also the comment recommended you install phantomJS as well. If you don’t have these packages you will need to install them.
library(geoR)
library(phantomJS)
data(gambia)
I have a shiny app that plots data from an API on a leaflet map. It also takes 2 inputs from the user that are passed through to the API call.
One of those is a text input that sets the region for which the API should pull data. If the user types in an incorrect region code or simply deletes the code, the shiny app gives an error and then you have to type in a correct code and wait for the app to get back on track. It's clumsy and looks bad.
I tried to get around it by using if(is.null(APIdata())) with an if{}else{} (see code below), but this literally did not change anything. I thought it would work, and I'm fine with the idea of it just popping back to an empty leaflet. Is there something else I can do?
Error:
Error: parse error: premature EOF
(right here) ------^
and
Warning: Error in : parse error: premature EOF
(right here) ------^
Stack trace (innermost first):
96: parse_string
95: parseJSON
94: fromJSON_string
93: jsonlite::fromJSON
92: ebird_GET
91: ebirdnotable
90: <reactive:APIdata> [/Users/Guest/Desktop/eBirdRarity/app.R#41]
79: APIdata
78: func [/Users/Guest/Desktop/eBirdRarity/app.R#68]
77: origRenderFunc
76: output$myMap
1: runApp
Code:
library(shiny)
library(shinydashboard)
library(shinythemes)
library(leaflet)
library(leaflet.extras)
library(rebird)
ui <- bootstrapPage(
theme = shinytheme("superhero"),
# Setting map to full-screen
tags$style(type="text/css", "html, body {width:100%;height:100%}"),
# Initializing leaflet output
leafletOutput("myMap", width="100%", height="100%"),
# Adding title overlayed on leaflet map
absolutePanel(top = 1, left = 50, draggable = T,
titlePanel("eBird Recent Rarities Viewer")),
# Adding slider input overlayed on leaflet map
absolutePanel(bottom = 1, left = 45, draggable = T,
sliderInput("slider_in", "Days Back", min = 1, max = 30, value = 14, round = T)),
# Adding text input overlayed on leaflet map
absolutePanel(top = 1, right = 45, draggable = T,
textInput("region_in", "Region Code", value = "US-MA", placeholder = "US-MA"))
)
server <- function(input, output) {
# Rendering data frame from API with slider input
APIdata <- reactive({
# Initial fetch of data from eBird API
a <- ebirdnotable(region = as.character(input$region_in), back = as.numeric(input$slider_in))
# Changing review status from logical to numeric
cols <- sapply(a, is.logical)
a[,cols] <- lapply(a[,cols], as.numeric)
# Initializing new date column
a["date"] <- format(strptime(a$obsDt, format = "%Y-%m-%d"), "%b %d")
# Initializing new color grouping column
a["group"] <- NA
# Assigning colors by review status
idx<- (a$obsReviewed == 0) # Not reviewed
a$group[idx] <- "white"
idx<- (a$obsReviewed == 1) & (a$obsValid == 1) # Reviewed and accepted
a$group[idx] <- "green"
# Jittering lat/lon points to fix point overlap
a$lat = jitter(a$lat, factor = 3)
# print(a)
return(a)
})
# Leaflet map
output$myMap = renderLeaflet({
if(is.null(APIdata()))
{
# Rendering leaflet map
return(leaflet() %>% addTiles()) %>%
addSearchOSM(options = searchOSMOptions(zoom = 8))
}
else
{
# Splitting up by review status in order to show reviewed on top
notReviewed = APIdata()[APIdata()$group == "white",]
accepted = APIdata()[APIdata()$group == "green",]
# Rendering leaflet map
leaflet() %>% addTiles() %>%
addCircleMarkers(data = notReviewed, color = "white", opacity = 0.7, label = paste(notReviewed$comName,", ",notReviewed$date, ", ", notReviewed$locName,sep = "")) %>% # , labelOptions = labelOptions(noHide = F, direction = 'auto')) %>%
addCircleMarkers(data = accepted, color = "green", opacity = 0.7, label = paste(accepted$comName,", ",accepted$date, ", ", accepted$locName, sep = "")) %>% # , labelOptions = labelOptions(noHide = F, direction = 'auto')) %>%
addLegend(position = "bottomright",
colors = c("#FFFFFF", "#008000"),
labels = c("Not reviewed", "Accepted"),
title = "Legend: review status", opacity = 1) %>%
addSearchOSM(options = searchOSMOptions(zoom = 8))
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
You could just validate if you are getting a tibble with values or if you are getting an empty tibble. In case the tibble is empty you can return NULL. This way the validation you have added to check if APIdata() is NULL would work.
You could just add if(length(a) == 0){return(NULL)} after a <- ebirdnotable(region = as.character(input$region_in), back = as.numeric(input$slider_in)) in your reactive for it to work.
EDIT:
As you mentioned in your comment you can actually use try here. That would mean adding one more condition in addition to above condition the code would be something like this:
a <- try(ebirdnotable(region = as.character(input$region_in), back = as.numeric(input$slider_in)))
if(class(a) == "try-error" ||length(a) == 0){return(NULL)}
Hope it helps!
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv")
df$hover <- with(df, paste(state, '<br>', "Beef", beef, "Dairy", dairy, "<br>",
"Fruits", total.fruits, "Veggies", total.veggies,
"<br>", "Wheat", wheat, "Corn", corn))
# give state boundaries a white border
l <- list(color = toRGB("white"), width = 2)
# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)
p <- plot_geo(df, locationmode = 'USA-states') %>%
add_trace(
z = ~total.exports, text = ~hover, locations = ~code,
color = ~total.exports, colors = 'Purples'
) %>%
colorbar(title = "Millions USD") %>%
layout(
title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = g
)
p
The above code is from plotly website and the plot produced should be as follows:
However, the plot I generated by using the code is as follows:
What happens? Do I need to install some other packages to reproduce the correct plot?
I got this too. If you open the javascript console you can see an error:
Failed to load resource: Unable to init SSL Context:
while it is trying to open this file:
"https://cdn.plot.ly/world_110m.json"
Here is a screen shot:
Cause:
I believe this is because the non-professional Version of R-Studio does not support https by design, so there is probably no work around except wrapping it as markdown and viewing it in a browser as I describe below.
Workaround:
If you package it in R-markdown (put your code between the following lines):
```{r}
(your code here)
```
and then save it as an .Rmd file) and knit it. Then it will still not work in the R-Studio preview-browser, and but it does if you use the "Open in Browser" function and open it in Chrome (for example).
Or buy the professional version :).