Published
Edited
Dec 8, 2018
4 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
update(currentData)
Insert cell
{
d3.select(chart).append("g")
.attr('id', 'vis')
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.append('rect')
.attr("width", width - (margin.left + margin.right))
.attr("height", height - (margin.top + margin.bottom))
.attr('fill', 'yellow')
.attr('fill-opacity', 0.05)
setScale(initialData)
initAxis()

return md`Add group 'vis' and init axes.`
}
Insert cell
function initAxis() {
let vis = d3.select(chart)
vis.append("g")
.attr("id", "xaxis")
.attr("transform", "translate(" + 0 + "," + (height- margin.bottom) + ")")
.call(xAxisCall)

vis.append("g")
.attr("id", "yaxis")
.attr("transform", "translate("+[margin.left, margin.top]+")")
.call(yAxisCall)
}
Insert cell
function update(data){
setScale(data)

let vis = d3.select('#vis'),
tr = d3.transition()
.duration(4000)
.ease(d3.easeQuad),
u = vis.selectAll("circle")
.data(data);
u.enter()
.append("circle")
.attr("cx", (d) => xScale(d.x))
.attr("cy", (d) => yScale(50))
.transition(tr)
.attr("cy", (d) => yScale(d.y))
.attr("fill", (d) => col(d.y))
.attr("r", 3.5);
u
.transition(tr)
.attr("cx", (d) => xScale(d.x))
.attr("cy", (d) => yScale(d.y))
// exit will not run because array lengths are consistent
u.exit()
.transition(tr)
.attr("cy", 0)
.remove();
updateAxis()
}
Insert cell
function setScale(data){
let rgx = d3.extent(data, d => d.x).reduce((a,b) => b-a)*0.1
xScale.domain(
[
d3.min(data, d => d.x)-rgx,
d3.max(data, d => d.x)+rgx
]
).nice();
xScale.range([margin.left, width-(margin.right+margin.left)])

let rgy = d3.extent(data, d => d.y).reduce((a,b) => b-a)*0.1
yScale.domain(
[
d3.min(data, d => d.y)-rgy,
d3.max(data, d => d.y)+rgy
]
).nice();
yScale.range([height - (margin.bottom+margin.top),margin.bottom])
xAxisCall.scale(xScale)
yAxisCall.scale(yScale)
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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