../../../data/GHE/mpn/deployment/deployments/2021-04-02/vignettes/learning_d3.Rmd
learning_d3.Rmd
There are a number of excellent resources available for learning how to do data visualization with D3, including online tutorials, self-paced courses, and books. There are also sites that provide numerous examples to learn from. We’ll enumerate these resources below as well as provide some tips on mapping the example D3 code you’ll encounter back to code that works with r2d3.
There are a number of books about D3 available, but only one has been updated to work with more recent versions of D3 (versions 4 and 5). That book is Scott Murray’s Interactive Data Visualization for the Web: An Introduction to Designing with D3. The book covers D3 from the ground up, presuming no existing experience with data visualization or web development.
The book covers bar charts, scatter plots, pie charts, stacked bar charts, force-directed graphs, and geographic visualizations. The books includes over 140 examples as well as case studies with nine accomplished designers talking about their D3-based projects.
There are several good self paced online tutorials for learning D3 available, these include:
There are also a number of websites that aggregate examples of D3 visualizations, these include:
When you are learning D3 or translating D3 examples for use with R it’s important to keep in mind that D3 examples will generally include code to load data, create an SVG or other root element, and establish a width and height for the visualization. On the other hand with r2d3, these variables are provided automatically so do not need to be created. Here is some code you’ll typically see in D3 examples:
Creating an SVG element to contain the visualization:
Hard-coding margins, width, and height for the visualization:
var margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
Loading data for the visualization:
Code like the above isn’t necessary with r2d3, since the following variables are provided automatically to your D3 script:
data
— The R data converted to JavaScript.svg
— The svg container for the visualizationwidth
— The current width of the containerheight
— The current height of the containeroptions
— Additional options provided by the usertheme
— Colors for the current themeFor example, here’s a simple r2d3 script which makes use of these automatically provided variables:
// !preview r2d3 data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20)
var barHeight = Math.floor(height / data.length);
svg.selectAll('rect')
.data(data)
.enter().append('rect')
.attr('width', function(d) { return d * width; })
.attr('height', barHeight)
.attr('y', function(d, i) { return i * barHeight; })
.attr('fill', 'steelblue');