# template elements
2018-04-11
Bobae Kang
(Bobae.Kang@illinois.gov)
Source: Wikimedia Commons
rgdal
pacakge
“A shapefile is a simple, nontopological format for storing the geometric location and attribute information of geographic features. Geographic features in a shapefile can be represented by points, lines, or polygons (areas).”
- “What is a shapefile?”, Esri“The shapefile format is a popular geospatial vector data format for geographic information system (GIS) software […] developed and regulated by Esri […]. The shapefile format can spatially describe vector features: points, lines, and polygons […]. Each item usually has attributes that describe it, such as name or temperature.” - “Shapefile”, Wikipedia
A shapefile format in fact consists of a collection of files. The following are commonly included when using shapefile data in R:
File extension | Description |
---|---|
.shp |
The main file that stores the feature geometry; required. |
.shx |
The index file that stores the index of the feature geometry; required. |
.dbf |
The dBASE table that stores the attribute information of features; required. |
.prj |
The file that stores the coordinate system information; used by ArcGIS. |
library(rgdal)
spatial_object <- readORG(dsn, layer)
# example:
# il_counties <- read(dsn = "shapefiles", layer = "il_counties")
readORG
function imports a shapefile into R environment
dsn
is the path to the directory with a shapefile to importlayer
is the name of a shapefile to import Spatial*
classes
Points
, MultiPoints
, Pixels
, Grid
, Lines
, Polygons
Spatial*DataFrame
classes
data.frame
table can be accessed using standard methods.class(counties)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"
icjiar
package provides a spatial object named counties
for countes in Illinois
SpatialPolygonsDataFrame
classtmap
package for thematic mapsleaftlet
package for interactive mapsSource: tmap GitHub repo
“With the tmap package, thematic maps can be generated with great flexibility. The syntax for creating plots is similar to that of ggplot2. The add-on package tmaptools contains tool functions for reading and processing shape files.” - “tmap in a nutshell”
tmap
is the most accessible R package for generating maps, making it easy to get visually appealing maps using data in the shapefile format.qtm(shape_object, ...)
qplot()
in ggplot2
qtm(counties, fill = "circuit")
tm_shape(shape_object) +
tm_*() # add tmap elements as layers
tm_shape
takes a spatial “shape object”Base tmap
drawing layers
Drawing layer | Description | Aesthetics |
---|---|---|
tm_polygons |
Draws polygons | col |
tm_symbols |
Draws symbols | size, col, shape |
tm_lines |
Draws lines | col, lwd |
tm_raster |
Draws a raster | col |
tm_text |
Add text labels | text, size, col |
The table is duplicated from a tmap vignette page
Derived tmap
drawing layers
Drawing layer | Description | Aesthetics |
---|---|---|
tm_fill |
Fills the polygons | see tm_polygons |
tm_borders |
Draws polygon borders | none |
tm_bubbles |
Draws bubbles | see tm_symbols |
tm_squares |
Draws squares | see tm_symbols |
tm_dots |
Draws dots | see tm_symbols |
tm_markders |
Draws markers | see tm_symbols and tm_text |
tm_iso |
Draws iso/contour lines | see tm_lines and tm_text |
The table is duplicated from a tmap vignette page
tmap
attribute layers
Attribute layer | Description |
---|---|
tm_grid |
Add coordinate grid lines |
tm_credits |
Add credits text label |
tm_compass |
Add map compass |
tm_scale_bar |
Add scale bar |
The table is duplicated from a tmap vignette page
tm_shape(counties) +
tm_borders() +
tm_fill(col = "circuit")
tm_layout(title = NA, scale = 1, title.size = 1.3, bg.color = "white", aes.color = c(fill = "grey85", borders = "grey40", symbols = "grey60", dots = "black", lines = "red", text = "black", na = "grey75"), ...)
tm_layout
is the general function to control all things about layout settings.tm_style_*
functions which offer predefined sets of styling-related layout settings such as background colors, colors and font (similar to ggplot2
themes).tm_format_*
functions which offer predefined sets of position-related layout settings such as margins.Predefined styles
Style | Description |
---|---|
tm_style_white |
White background, commonly used colors (default) |
tm_style_gray |
Gray background, useful to highlight sequential palettes (e.g. in choropleths) |
tm_style_natural |
Emulation of natural view: blue waters and green land |
tm_style_bw |
Greyscale |
tm_style_classic |
Classic styled maps |
tm_style_col_blind |
Style for colorblind viewers |
tm_style_cobalt |
Inspired by latex beamer style cobalt |
tm_style_albatross |
Inspired by latex beamer style albatross |
tm_style_beaver |
Inspired by latex beamer style beaver |
tm_shape(counties) +
tm_borders() +
tm_fill(col = "circuit") +
tm_style_classic()
Predefined formats
Format | Description |
---|---|
tm_format_World |
Format specified for world maps |
tm_format_World_wide |
for world maps with more space for the legend |
tm_format_Europe |
for maps of Europe |
tm_format_Europe_wide |
for maps of Europe with more space for the legend |
tm_format_NLD |
for maps of the Netherlands |
tm_format_NLD_wide |
for maps of the Netherlands with more space for the legend |
tm_shape(counties) +
tm_borders() +
tm_fill(col = "circuit") +
tm_format_World_wide()
tmap_mode("plot") # set to static "plot" mode
tmap_mode("view") # set to interactive "view" mode
ttmp() # toggle between modes
leaflet
map
tm_view()
is a function to specify options for “view” modetmap_leaflet()
can directly generate an interactive leaflet
map tmap_mode("view")
qtm(counties, fill = "circuit")
Source: leafletjs.com
“Leaflet is one of the most popular open-source JavaScript libraries for interactive maps. It's used by websites ranging from The New York Times and The Washington Post to GitHub and Flickr, as well as GIS specialists like OpenStreetMap, Mapbox, and CartoDB.”
-“Leaflet for R”, RStudio
leaflet
is a powerful library for generating interactive maps, it takes much time and practice to get familiar with its API.tmap
's interactive view could be an alterantive to using leaflet
's API directly.pal <- colorFactor(topo.colors(5), counties$circuit)
leaflet(counties) %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(fillColor = ~pal(circuit), color = "darkgrey", weight = 2) %>%
addLegend(pal = pal, values = ~circuit)
sp::spplot()
ggplot2::geom_map()
ggmap
leaftlet
official documentation pagetmap
github repository
Source: Wikipedia Commons
ggiraph
: an htmlwidget
package for interactive ggplot2
graphicsplotly
: R API for the plotly.js libraryhighcharter
: R API for the highchart.js librarySource: ggiraph documentation page
“ggiraph is an htmlwidget and a ggplot2 extension. It allows ggplot graphics to be animated.”
- Gohel, D. (package author/creator)
ggiraph
offers interactive “geoms” to be used for a ggplot2
plot and renders the plot with interactive “geoms” as an interactive visualization.
p <- plot + geom_*_interactive(...)
ggiraph(code = print(p), ...)
plot
is a ggplot
objectggiraph()
takes a ggplot2::ggplot
object with an interactive “geom” to generate an interactive plotggplot
object:
aes(tooltip, onclick, data_id)
tooltip
is a column containing information to be displayed as tooltiponclick
is a column containing JavaScript instructions to run for a “click” eventdata_id
is a column containing id to be associated with elements.
data <- ispcrime %>% filter(county != "Cook") %>% left_join(regions)
p <- ggplot(data, aes(x = violentCrime, propertyCrime, color = region)) +
geom_point_interactive(aes(tooltip = county, data_id = county))
ggiraph(code = print(p), hover_css = "fill:orange;fill-opacity:.3;cursor:pointer;")
Source: wikimedia.org
“Plotly's R graphing library makes interactive, publication-quality graphs online. Examples of how to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, and 3D (WebGL based) charts.”
- “Plotly R Library”, plotly
ggplotly(p = ggplot2::last_plot(), ...)
ggplotly()
provides a quick and easy way to convert a ggplot
object into an interactive plotly objectp
is a ggplot2::ggplot
object to be made interactive
p
is the most recently created ggplot
object if there is any# using the same data
p <- ggplot(data, aes(violentCrime, propertyCrime, colour = region)) +
geom_point() + labs(title = "Using ggplotly()")
ggplotly(p)
plot_ly(data, x, y, color, alpha, symbol, size, ...)
# equivalent to add_type()
add_trace(p, ..., type = "type", inheret = TRUE)
plot_ly
takes a data frame and defines the aesthetic mappingsplot_ly
interface, which adds a layer to the plot output
plot_ly
can define traces, using add_trace()
and its variants make it possible to use a dplyr
-style workflow with pipe operatorsp
Function | Description | Equivalent to add_trace(...) |
---|---|---|
add_trace() |
add traces with options | NA |
add_markers() |
adds a scattorplot | type="scatter", mode="markers" |
add_lines() |
adds a line plot | type="scatter", mode="lines" |
add_bars() |
adds a bar plot | type="bar", mode="markers" |
add_histogram() |
adds a histogram | type="histogram" |
add_boxplot() |
adds a box plot | type="box" |
add_pie() |
adds a pie chart | type="", mode="" |
add_text() |
adds texts | |
add_polygons() |
adds polygons | type="", mode="" |
plot_ly(data, x = ~violentCrime, y = ~propertyCrime, color = ~region) %>%
add_markers() %>%
layout(title = "Using plot_ly() interface")
“Highcharter is a R wrapper for Highcharts javascript libray and its modules. Highcharts is very mature and flexible javascript charting library and it has a great and powerful API.”
-Kunst, J. (package author)
Highcharts
plots in ICJIA R&A Unit's online articles (e.g. Figure 1 and Figure 2 in this article).hchart(data, type, hcaes(x, y, ...))
qplot()
in ggplot2
type
specifies the type of plot (e.g. “scattor” for scattorplot)hcaes()
works like aes()
in ggplot2
# using the same data
hchart(data, type = "scatter", hcaes(x = violentCrime, y = propertyCrime, group = region)) %>%
hc_title(text = "Using hchart() interface")
highchart() %>%
hc_add_series(...) %>% # add a "series"
hc_xAxis(...) %>% # define x-axis
hc_yAxis(...) %>% # define y-axis
hc_title(...) %>% # add the main title
hc_chart(...) %>% # modify general plot options
hc_color(...) %>% # control colors
hc_*(...) # and more...
highchart() %>%
hc_add_series(data, type = "scatter", hcaes(x = violentCrime, y = propertyCrime, group = region)) %>%
hc_title(text = "Using highchart() interface")
ggiraph
official documentation pagehighcharter
official documentation pageplotly
official documentation pageplotly
for R.rAmCharts
is an R interface to the amCharts
JavaScript library that offers interactive options for many common plot types and more.chartjs
is an R interface to the Chart.js
JavaScript library and offers six chart types (bar, line, pie, doughnut, radar, and polar area) for interactive plots.googleVis
offers an R API to Google Charts, which offers rich set of interactive charts and data tools.dygraphs
is an R interface to the dygraphs JavaScript library for interactive time-series plots.visNetwork
(wrapper for vis.js
) and networkD3
are two popular packages for interactive visualization of network/graph data in R. Start with igraph
or tidygraph
package to learn how to work with network objects in Rwordcloud2
(wrapper for worldcloud2.js
) is a package for creating word clouds, a popular way to visualize text data.data.tree
is an R package for managing as well as visualizing hierarchical data and tree structures.Source: Gifimage.net
References