Published
Edited
Oct 3, 2019
Insert cell
md`# d3 understanding`
Insert cell
d3 = require('d3')
Insert cell
data = d3.csv(
"https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
)
Insert cell
data2 = {
const x = [];
for (let i = 0; i < data.length; i++) {
x.push({
mpg: parseFloat(data[i].mpg),
disp: parseFloat(data[i].disp),
cyl: parseFloat(data[i].cyl)
});
}
return x;
}
Insert cell
w = 650
Insert cell
h = 500
Insert cell
margin = 50
Insert cell
canvas = html``
Insert cell
container = d3
.create('svg')
.attr('width', w)
.attr('height', h)
Insert cell
cont = container.node()
Insert cell
d3
.select(cont)
.append('svg')
.attr('width', w)
.attr('height', h)
.selectAll('circle')
.data(data2)
.enter()
.append('circle')
.attr('cx', d => {
return d.disp;
})
.attr('cy', d => {
return d.mpg;
})
.attr('r', 5)
Insert cell
cont2 = d3
.create('svg')
.attr('width', w)
.attr('height', h)
Insert cell
cont3 = cont2.node()
Insert cell
data3 = [
5,
10,
13,
19,
21,
25,
22,
18,
15,
13,
11,
12,
15,
20,
18,
17,
16,
18,
23,
25
]
Insert cell
bar_padding = 1
Insert cell
svg_bar = d3
.select(cont3)
.append('svg')
.selectAll("rect")
.data(data3)
.enter()
.append('rect')
.attr('x', (d, i) => {
return i * (w / data3.length);
})
.attr('y', d => {
return h - d;
})
.attr('width', w / data3.length - bar_padding)
.attr('height', d => {
return d * 10;
})
.attr('fill', d => {
return "rgb(0,0, " + d * 10 + ")";
})
Insert cell
cont4 = d3
.create('svg')
.attr('width', w)
.attr('height', h)
Insert cell
cont5 = cont4.node()
Insert cell
svg_scatter = d3
.select(cont5)
.append('svg')
.selectAll('circle')
.data(data2)
.enter()
.append('circle')
.attr('cx', d => {
return d.disp;
})
.attr('cy', d => {
return d.mpg;
})
.attr('r', 10)
.attr('fill', 'black')
.append('g')
.call(d3.axisBottom(x_scale))
.call(d3.axisLeft(y_scale))
Insert cell
svg_scatter
Insert cell
md`
> Scales are functions that map from an input domain to an output range

`
Insert cell
mpg_domain = d3.extent(data2[1])
Insert cell
x = [1, 2, 3, 4]
Insert cell
mpg_extent = d3.extent(data2, d => {
return d.mpg;
})
Insert cell
disp_ext = d3.extent(data2, d => {
return d.disp;
})
Insert cell
x_scale = d3
.scaleLinear()
.domain([60, 400])
.range([0, w]) // creates a linear scale
Insert cell
y_scale = d3
.scaleLinear()
.domain([10, 30])
.range([h, 0])
Insert cell
x_axis = d3.axisBottom(x_scale)
Insert cell
y_axis = d3.axisLeft(y_scale)
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