Jekyll, R Markdown and Plotly (Fulton County Example)
R Markdown and Plotly
Saul Cruz
July 8 2017 Saul Cruz
Objective
In this post, I’ll show a very simple example of how to use plotly using R and Jekyll. This post will basically demonstrate the function plot_ly().
For more information please refer to Plot_ly R Documentation
Pre-requisites
install.packages(plotly)
Dataset
The dataset used for this exploratory analysis can be found in Fulton Conuty Open Data and represents the base (ground-level) outline, or footprint, of buildings and other man-made structures in Fulton County, Georgia.
I download the data using getURL() and load it into a dataframe.
Exploratory Analysis using Plotly
This simple example shows the use of add_lines() , this function connects x/y pairs with lines in the order of their x values, it is very helpful when plotting time series, for more information about it and some more examples please refer to the Plot_ly interface
Below, there’s an example that helps us to understand how many buildings have been built over time in Fulton, County, Georgia.
I do a simple count by year using the table() function, and I convert it back to DataFrame to easily visualize it.
data_count_by_year<-data.frame(table(data$YearBuilt))
colnames(data_count_by_year) <- c("Year", "No.Buildings")
p1 <- plot_ly(data_count_by_year, x = ~Year, y = ~No.Buildings) %>%
add_lines(name = "No.Buildings") %>%
layout(title="# of Buildings over time in Fulton, Georgia")
p1
Jekyll
To be able to display this plot I convert the elements to html. using the following function knit_htmlwidgets(“2017-07-08-Plotly_Example.Rmd”), this function converts the .Rmd file to html, and after that you can just call the html file from your post markdown file in jekyll. Thanks to Ben Cunningham and Brendan Rocks, Ben’s example really helped me to get where I needed.
knit_htmlwidgets <- function(input,
output_dir = "./_includes/htmlwidgets",
...) {
file_name <- rev(unlist(strsplit(input, split = "/")))[1]
path <- rmarkdown::render(input, "html_document", output_dir = output_dir)
remove_doctype(path)
}
remove_doctype <- function(input) {
html_lines <- readLines(input)
keep <- grep("^<!DOCTYPE html>$", html_lines, invert = TRUE)
writeLines(html_lines[keep], input)
}
References
Coursera Week 3 (R Markdown) Product Development Tools