Published
Edited
Sep 15, 2021
1 fork
Insert cell
# D3 Drawing Part 1
Functionally; declaratively;
Virginia Tech, CS 5764
Insert cell
md`**Review:**
* What is the purpose of visualization?
* What are the two steps to map data to visualization?
1. rows --> Marks (PLAV)
2. columns --> Channels (x, y, color, size, ...) `

Insert cell
md`**Resources:**
* D3: https://d3js.org
* D3 joins: https://observablehq.com/@d3/learn-d3-joins
* D3 shapes: https://observablehq.com/@d3/learn-d3-shapes
* D3 scales and axes: https://observablehq.com/@d3/learn-d3-scales
* Axes API: https://github.com/d3/d3-axis
* Scales API: https://github.com/d3/d3-scale
* Color scales API: https://github.com/d3/d3-scale-chromatic
* D3 color legends: https://observablehq.com/@d3/color-legend
* D3 gallery: https://observablehq.com/@d3/gallery
* Murray chapters 6, 7, 8

**Technology stack:**
* HTML5, DOM, CSS, SVG, JavaScript, D3, Observable
* D3 in JS vs. D3 in Observable?
`
Insert cell
svg = html`
<svg width="400" height="200" style="border:1px solid black">
<circle cx="100" cy="100" r="50" fill="red"/>
<rect x='100' y='50' width='100' height='30' fill='steelblue'>
</svg>`

Insert cell
md ` styles can be defined with an html declarative form and thus available `

Insert cell
md`### D3 SVG`

Insert cell
d3 = require("d3@6")
Insert cell
md`### D3 data`
Insert cell
data = d3.csvParse(await FileAttachment("States2010.csv").text(), d3.autoType)
.sort( (a,b) => b.PercentCollegeGrad - a.PercentCollegeGrad)
Insert cell
md`## D3 drawing
Scaling: Domain &rarr; Range`
Insert cell
d3.extent(data, d=>d.IncomePerCapita)

Insert cell
{
var element = html`
<svg width="800" height="300" style="border:1px solid black" >
</svg>`;
var svg = d3.select(element);
// scaling functions here for
// yScale
// and cScale

// D3 stuff here... functional style ... chaining operations
//
svg.selectAll('rect')
.data(data).join('rect') // map rows to rects
// map index to x channel .attr('x', (d,i) => i * 15)
// give a size factor for width .attr('width', 13)
// percent col grad -> 'height' channel
//
// map y position
// income per capita to color saturation
// add some text to the chart
// rects.append('title').text((d,i) => d.Abbrev + ' ' + d.PercentCollegeGrad + ' ' + d.IncomePerCapita);
return element;
}
Insert cell
import {legend} from '@d3/color-legend'
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more