Having trouble plotting location variable in R using googleVis package? - r

So I have this dataset of bike thefts (link: https://www.opendataphilly.org/dataset/bicycle-thefts/resource/f9809381-76f6-4fca-8279-621e088ddaa0).
I tried this code to plot location variable in R. the code runs, and i am taken to a new window but it is blank. Nothing appears.
What am I doing wrong?
Here's what I tried:
I renamed the dataset as bt
install.packages("ggmap")
library(ggmap)
install.packages("googleVis")
library(googleVis)
bt$LOCATION_B <- as.character(bt$LOCATION_B)
bt$geom <- gsub(",", ":", bt$geom)
placeNames <- as.character(bt$LOCATION_B)
plotData <- data.frame(name = placeNames, latLong = unlist(bt$geom))
sites <- gvisMap(plotData, locationvar = "latLong", tipvar = "name",
options = list(displayMode = "Markers", mapType = "terrain",
colorAxis = "{colors:['red', 'blue']}", height = 600,
useMapTypeControl=TRUE, enableScrollWheel='TRUE'))
plot(sites)

Related

How to optimize this R script to use the minimum CPU and Memory possible

I built this R script that generate a map and a background tiles, the problem is, I need to run it on PowerBI service, which has a very constrained resources (Ram and CPU), I attached a reproducible example
This example works fine in PowerBI service, but when I tried it with my real data only the raster or the map works, but when I do both, I get you exceed the resource available, and as it is not documented, I don't know if the issue is CPU or RAM.
what's the best way to profile this code and check which section to change
please notice the dataset is a raster saved as ASCII, using saveRDS, it is done outside PowerBI and loaded as a csv file, as PowerBI does not read binary data
# Input load. Please do not change, the dataset is generated by PowerBI, I change it only to have a reproducible example #
`dataset` = read.csv('https://raw.githubusercontent.com/djouallah/loadRobjectPBI/master/powerbidf.csv', check.names = FALSE, encoding = "UTF-8", blank.lines.skip = FALSE);
# Original Script. Please update your script content here and once completed copy below section back to the original editing window #
library(sf)
library(dplyr)
library(tmap)
library(tidyr)
tempdf <- dataset %>%
filter(!is.na(Value))%>%
dplyr::select(Index,Value)%>%
arrange(Index)%>%
mutate(Value = strsplit(as.character(Value), "#")) %>%
unnest(Value)%>%
dplyr::select(Value)
write.table(tempdf, file="test3.rds",row.names = FALSE,quote = FALSE, col.names=FALSE)
rm(tempdf)
background <- readRDS('test3.rds', refhook = NULL)
dataset <- dataset[c("x","y","color","status","labels")]
dataset$color <- as.character(dataset$color)
dataset$labels <- as.character(dataset$labels)
map <- st_as_sf(dataset,coords = c("x", "y"), crs = 4326)
chartlegend <- dataset %>%
dplyr::select(status,color)%>%
distinct(status, color)%>%
arrange(status)
rm(dataset)
tm_shape(background)+
tm_rgb() +
rm(background)+
tm_shape(map) +
tm_symbols(col = "color", size = 0.04,shape=19)+
tm_shape(filter(map, !is.na(labels))) +
tm_text(text="labels",col="white")+
rm(map)+
tm_add_legend(type='fill',labels=chartlegend$status, col=chartlegend$color)+
tm_layout(frame = FALSE,bg.color = "transparent",legend.width=2)+
tm_legend(position=c("left", "top"),text.size = 1.3)+
rm(chartlegend)
changing the code to use base R only did help a bit
# Input load. Please do not change #
`dataset` = read.csv('https://raw.githubusercontent.com/djouallah/loadRobjectPBI/master/powerbidf.csv', check.names = FALSE, encoding = "UTF-8", blank.lines.skip = FALSE);
# Original Script. Please update your script content here and once completed copy below section back to the original editing window #
library(sf)
library(tmap)
tempdf <- dataset[dataset$Value!="",]
tempdf <- tempdf[c("Index","Value")]
tempdf <- tempdf[order(tempdf$Index),]
tempdf <- stack(setNames(strsplit(as.character(tempdf$Value),'#'), tempdf$Index))
tempdf <- tempdf["values"]
write.table(tempdf, file="test3.rds",row.names = FALSE,quote = FALSE, col.names=FALSE)
rm(tempdf)
background <- readRDS('test3.rds', refhook = NULL)
dataset <- dataset[c("x","y","color","status","labels")]
dataset$color <- as.character(dataset$color)
map <- st_as_sf(dataset,coords = c("x", "y"), crs = 4326)
chartlegend <- unique(dataset[c("status","color")])
rm(dataset)
tm_shape(background)+
tm_rgb() +
rm(background)+
tm_shape(map) +
tm_symbols(col = "color", size = 0.04,shape=19)+
tm_text(text="labels",col="white")+
rm(map)+
tm_add_legend(type='fill',labels=chartlegend$status, col=chartlegend$color)+
tm_layout(frame = FALSE,outer.margins = c(0.005, 0.6, 0.06, 0.005),bg.color = "transparent",legend.width=2)+
tm_legend(position=c("right", "top"),text.size = 1.3)+
rm(chartlegend)

R- visNetwork - graph doesn't show edges

I have a code that looks like this:
setwd("C:/Users/Evangelista/Desktop/v1")
require(visNetwork)
require(dplyr)
require(shiny)
require(magrittr)
graf.info = read.csv("nodes.csv")
id <- rownames(graf.info)
graf.info <- (cbind(id=id, graf.info))
graf.powiazania = read.csv("edges.csv")
visNetworkNodes <- data.frame(graf.info) %>%
mutate(id=graf.info$id,
label = nazwa_agenta,
title = nazwa_agenta)
visNetworkLinks <- data.frame(from = graf.powiazania$From,
to = graf.powiazania$To,
width = 50,
arrows = list(to = list(enabled = TRUE, scaleFactor = 4)))
net <- visNetwork(nodes = visNetworkNodes,
edges = visNetworkLinks,
height = "600px",
width = "800px")
net
And my problem is that the graph doesn't display any edges. My data is taken from csv file and it looks like this:
I don't know what is wrong with it. My data looks correct to me, data frame with nodes also has the column id. Data frame with edges has "From" and "To" columns. I run out of ideas what went wrong.
I found a solution :
visNetworkNodes <- data.frame(graf.info) %>%
mutate(id=graf.info$nazwa_agenta, <------here i changed 'id' to 'nazwa_agenta'
label = nazwa_agenta,
title = nazwa_agenta)

Connecting Spatial points with directed lines using PlotGoogleMaps package in R

I have been trying to do some dynamic Google Map plots from R using the PlotGoogleMaps package. I have no problem in plotting the Spatial Points on google maps using this package.
I want to connect some pairs of the spatial points plotted with lines. I could not find any way to do that in R with the package. It seems that Google Maps has a function for that in the API: google.maps.Polyline.
Could anyone help with how this can be done in R? I referred to links like How to get image iconMarker working for plotGoogleMaps R? to make sure that my basic plot is working fine. How can I join them to show a path?
I ran the code below
library(plotGoogleMaps)
vessels = data.frame(id = c(1:10)
, lat = c(22.0959, 22.5684, 21.9189, 21.8409, 22.4663, 22.7434, 22.1658, 24.5691, 22.4787, 22.3039)
, lon = c(114.021, 114.252, 113.210, 113.128, 113.894, 114.613, 113.803, 119.730, 113.910, 114.147))
group1 = vessels[1:5,]
group2 = vessels[6:10,]
coordinates(group1) = ~ lon + lat
proj4string(group1) = CRS("+proj=longlat +datum=WGS84")
group1 <- SpatialPointsDataFrame( group1 , data = data.frame( ID = row.names( group1 ) ))
coordinates(group2) = ~ lon + lat
proj4string(group2) = CRS("+proj=longlat +datum=WGS84")
group2 <- SpatialPointsDataFrame( group2 , data = data.frame( ID = row.names( group1 ) ))
m <- plotGoogleMaps(group1, legend = FALSE, layerName = "Vessels 1"
, add =T,
iconMarker=rep('http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png',nrow(group1) ),
mapTypeId='ROADMAP', filename = "out.htm")
m <- plotGoogleMaps(group2,legend = FALSE, layerName = "Vessels 2"
, previousMap = m , add = F
, iconMarker = rep('http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png',nrow(group2) )
, filename = "out.htm")
It works fine. But I do not know how to connect the plotted points to make a path between a selected pair of points on the map.
This doesn't directly answer your question, but I'm posting it as a potential alternative.
I've built the googleway package, which includes a Google Maps widget.
To use Google Maps you need a Google Maps API key
library(googleway)
vessels = data.frame(id = c(1:10)
, lat = c(22.0959, 22.5684, 21.9189, 21.8409, 22.4663, 22.7434, 22.1658, 24.5691, 22.4787, 22.3039)
, lon = c(114.021, 114.252, 113.210, 113.128, 113.894, 114.613, 113.803, 119.730, 113.910, 114.147))
vessels$group <- c(rep(1, 5), rep(2, 5))
## a google maps api key
map_key <- "your_api_key"
google_map(key = map_key, data = vessels) %>%
add_circles(radius = 1000) %>%
add_polylines(lat = 'lat', lon = 'lon', id = 'group',
mouse_over_group = 'group')

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