Interactive R Markdown Document with ggmap - r

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!

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)

How to Save as png with ChartJSRadar in R?

I'm trying to save my plot with resolution of 300 for publication purposes. The usual methods to save plots with png device isn't working and saves a blank png. Is there something else I can try, or a different package that does something similar?
library(radarchart)
data<-data.frame(Field=c("Age","Sex","Submission"), y=sample(1:100,3), x=sample(1:100,3))
path<-"C:\\Desktop\\R\\"
png(file=paste0(path,"Radar",".png"), width=500, height=500, res=300)
plot<-chartJSRadar(scores=data, labelSize= 10, main="Completeness Radar", maxScale = 100)
print(plot)
dev.off()
I've also tried:
png(file=paste0(path,"Radar",".png"), width=500, height=500, res=300)
chartJSRadar(scores=data, labelSize= 10, main="Completeness Radar", maxScale = 100)
dev.off()
library(radarchart)
library(webshot)
library(htmlwidgets)
dat <- data.frame(
Field = c("Age","Sex","Submission"),
y = sample(1:100,3),
x = sample(1:100,3)
)
plt <- chartJSRadar(
scores = dat,
labelSize= 10,
main="Completeness Radar",
maxScale = 100
)
saveWidget(plt, "plt.html")
webshot("plt.html")
magick::image_read("webshot.png")
radar charts are very difficult for folks to grok
data and plot are suberbad variable names
whitespace is your bff
webshot can limit target area
various magick ƒ()s can crop target area
consider using http://www.ggplot2-exts.org/ggradar.html

Having trouble plotting location variable in R using googleVis package?

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)

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.

embed rChart in Markdown

I am trying to embed a NVD3 chart in a Markdown document. I am on a Ubuntu64 system with RStudio 0.98.932, R 3.1.0, rCharts 0.4.2, the browser is Chrome.
The instructions/code from this link:
```{r}
library(rCharts)
library(knitr)
opts_chunk$set(comment = NA, results = "asis", comment = NA, tidy = F)
hair_eye_male = subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = 'Eye',
data = hair_eye_male, type = 'multiBarChart'
)
n1$set(width = 600)
# n1$show('iframesrc', cdn = TRUE) # option 1
# n1$show('inline', include_assets = TRUE, cdn = TRUE) # option 2
```
Neither of the options [n1$show] work, I just get code in a browser. Is there another way of including NVD3 documents in Markdown?
To get rCharts to work with knit2html, you will need to use the print method with the argument include_assets = TRUE. This is because knitr will not add the js and css assets required by an rCharts plot automatically. Here is a minimal working example.
## MorrisJS with Knit2HTML
```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```
Note that you need to use m1$print('chart2', include_assets = TRUE, cdn = TRUE) if you intend to publish your chart on RPubs, for otherwise the JS and CSS assets will be served from your local library.
Source:Knitr HTML in R Markdown
This code is working for me. I am using ubuntu64 and same config you mentioned.
```{r, echo=FALSE,results='asis',comment=NA}
library(rCharts)
hair_eye_male <- subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = "Eye", data = hair_eye_male, type = "multiBarChart")
n1$show('iframesrc',cdn=TRUE)
```
Note : you must write results='asis' and comment = NA in chunk options and not use opts_chunk$set as you have in your code block and what you pasted to copy.com.

Resources