Reproducing a Choropleth Map by using plotly package in R - r

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 :).

Related

How can I fix the following error in KnitR?

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)

Multiple variable observation plotly tooltip

I am working on making a plotly map of the US with hover tooltips which I have gotten to work somewhat. However, I have multiple observations per state for each variable I would like to display in the tooltip and currently only the first observation for each state is displayed. Each observation is the performance of a candidate in the 1976 presidential election in a state, and I would like the hover tooltip to display each candidates performance in the state instead of just the first candidate listed in that state.
Here is the code I am using at the moment.
candidate denotes the name of the candidate , state_share and round_share denote the percent of the state popular vote and state electoral votes the candidate receives respectively.
library(plotly)
colorscale <- c("blue" , "purple" , "red")
l <- list(color = toRGB("white"), width = 2)
# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = FALSE
)
threshold10$hover <- with(threshold10, paste(state, "<br>" , canvec ,':',
state_share ,",","Electoral Votes", round_share ))
fig <- plot_geo(subset(threshold10, year == 1976), locationmode = 'USA-states')
fig <- fig %>%
add_trace(
z = ~evotes, text = ~ hover , locations = ~state_po,
color = ~state_share , colors = colorscale) %>%
layout(title = '1976 Electoral Vote Allocation <br> 10% State Threshold',
geo = g)
fig
I'm also attaching an image of the dataset and the map produced by my code. I appreciate any help anyone has to offer. I am newish to working with plotly and mapping so if this is a simple question sorry about that. Thank you for your help.
dataframe:
map output:

Leaflet in FlexDasboard Won't Render Charts

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({})

plotting barchart in popup using leaflet library

Quick question all.
I have some data in sql server which i have loaded into RStudio. I have made a barchart for the data and now i am using leaflet library with the use of latitude and longitude to plot a point on the map. I want to be able to use popup to show a barchart in it when the user clicks on the point.
BarChart code (maybe this is a problem because i am using googleVis library so not sure if i can use this in the popup. but again this is the most appropriate bar graph i can make and need- other suggestions could be helpful as i am not a professional in R libraries yet)
Switzerland <- sqlQuery(con, "sql query")
SwitzerlandChart <- gvisBarChart(Switzerland, options = list(height=200))
For the graph plot the code is:
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addCircles(lng=8.498868, lat=46.9221, popup=paste(plot(SwitzerlandChart)))
When i run this code it opens a webpage to view my barplot.
Then i run the following:
m #Prints the graph
This prints the graph with the point in the desired location but the popup shows me a webpage instead which also only i can open.
I want to be able to plot the bargraph inside the popup please.
Hope someone can help
Maybe a little late but here's a solution. The addPopups() function in library(leaflet) seems to be able to handle .svg files. Therefore, you could simply save your plot using svg() and then read it again using readLines(). Here's a reproducible example using library(mapview):
library(lattice)
library(mapview)
library(sp)
data(meuse)
coordinates(meuse) <- ~x+y
proj4string(meuse) <- CRS("+init=epsg:28992")
clr <- rep("grey", length(meuse))
fldr <- tempfile()
dir.create(fldr)
pop <- lapply(seq(length(meuse)), function(i) {
clr[i] <- "red"
p <- xyplot(meuse$cadmium ~ meuse$copper,
col = clr, pch = 20, alpha = 0.7)
svg(filename = paste(fldr, "test.svg", sep = "/"),
width = 250 * 0.01334, height = 250 * 0.01334)
print(p)
dev.off()
tst <- paste(readLines(paste(fldr, "test.svg", sep = "/")), collapse = "")
return(tst)
})
mapview(meuse, popup = pop, cex = "cadmium")
You will see that each popup is a scatterplot. As for a leaflet example, consider this:
content <- pop[[1]]
leaflet() %>% addTiles() %>%
addPopups(-122.327298, 47.597131, content,
options = popupOptions(closeButton = FALSE)
)
In case you need the plot to be interactive, you could have a look at library(gridSVG) which is able to produce interactive svg plots from e.g. lattice or ggplot2 plots.
UPDATE:
library(mapview) now has designated functionality for this:
popupGraph: to embed lattice, ggplot2 or interactive hatmlwidgets based plots.
popupImage: to embed local or remote (web) images
This is currently only available in the development version of mapview which can be installed with:
devtools::install_github("environmentalinformatics-marburg/mapview", ref = "develop"
This may be a little late too, but here is a full leaflet implementation. I first create the plot and then use the popupGraph function to add it in.
# make a plot of the two columns in the dataset
p <- xyplot(Home ~ Auto, data = Jun, col = "orange", pch = 20, cex = 2)
# make one for each data point
p <- mget(rep("p", length(Jun)))
# color code it so that the corresponding points are dark green
clr <- rep("orange", length(Jun))
p <- lapply(1:length(p), function(i) {
clr[i] <- "dark green"
update(p[[i]], col = clr)
})
# now make the leaflet map
m1 <- leaflet() %>%
addTiles() %>%
setView(lng = -72, lat = 41, zoom = 8) %>%
# add the markers for the Jun dataset
# use the popupGraph function
addCircleMarkers(data = Jun, lat = ~Lat, lng = ~Lon,
color = ~beatCol(BeatHomeLvl), popup = popupGraph(p),
radius = ~sqrt(BeatHome*50), group = 'Home - Jun') %>%
# layer control
addLayersControl(
overlayGroups = c('Home - Jun'
),
options = layersControlOptions(collapsed = F)
) %>%
# legend for compare to average
addLegend('bottomright', pal = beatCol, values = last$BeatTotalLvl,
title = 'Compare<br>Quote Count to<br>3Mos State Avg',
opacity = 1)
m1
Here is the output.

Interactive R Markdown Document with ggmap

I'm working with the ggmap tutorial by Manuel Amunategui over at http://amunategui.github.io/ggmap-example/. It is a wonderful introduction to the ggmap package and thankfully I understand his tutorial.
However, I am also trying to make this material interactive through R markdown. When I run the below document, for some reason the rendering of the map is of very low quality. In my standard .R script the image produced is way better. Any thoughts as to what might cause the drastic difference in quality?
Also, in R Markdown, is it possible to have custom sizing of the images as well as placement? I am specifically interested in making the map larger and/or displaying another map with it side-by-side.
This first block of code is just to get your hands on the data if desired.
#install.packages("RCurl"); install.packages("xlsx"); install.packages("zipcode"); install.packages("ggmap")
library(RCurl)
library(xlsx)
# NOTE if you can't download the file automatically, download it manually at:
#'http://www.psc.isr.umich.edu/dis/census/Features/tract2zip/'
urlfile <-'http://www.psc.isr.umich.edu/dis/census/Features/tract2zip/MedianZIP-3.xlsx'
destfile <- "census20062010.xlsx"
download.file(urlfile, destfile, mode="wb")
census <- read.xlsx2(destfile, sheetName = "Median")
#census <- read.xlsx2(file = "census20062010.xlsx", sheetName = "Median")
head(census)
# clean up data
# census <- census[c('Zip','Median..', 'Pop')]
names(census) <- c('Zip','Median', 'Pop')
census$Median <- as.character(census$Median)
census$Median <- as.numeric(gsub(',','',census$Median))
census$Pop <- as.numeric(gsub(',','',census$Pop))
head(census)
# get geographical coordinates from zipcode
library(zipcode)
data(zipcode)
census$Zip <- clean.zipcodes(census$Zip)
census <- merge(census, zipcode, by.x='Zip', by.y='zip')
census$location <- paste0(census$city, ", ", census$state)
names(census) <- sapply(names(census), tolower)
# saved census to census.rdata at this point...
The next chunk of code below is what is in the markdown file.
```{r, message=FALSE, echo=FALSE}
library(ggmap)
library(ggplot2)
load("census.rdata")
inputPanel(
textInput("loc", label = "Location", value = "Orlando, FL"),
sliderInput("zoom", label = "Zoom Level",
min = 1, max = 12, value = 10, step = 1)
)
renderPlot({
census2 <- census[census$location == input$loc,]
map <- get_map(location = input$loc,
zoom = input$zoom,
maptype = 'roadmap',
source = 'google',
color = 'color',
filename = "ggmapTemp")
print(ggmap(map) +
geom_point(
aes(x=longitude, y=latitude,
show_guide = TRUE, size=Median),
data=census2, colour = I('red'), na.rm = T)
)
})
```
Thanks for your help!

Resources