Published
Edited
Mar 18, 2020
4 forks
1 star
Insert cell
Insert cell
Insert cell
Insert cell
data = d3.range(0, 10).map((d,i) => {
return {
Time: i,
Births: Math.random(),
Deaths: Math.random()
}})
Insert cell
Insert cell
keys = Object.keys(data[0]).slice(1)
Insert cell
Insert cell
stack = d3.stack().keys(keys)(data)
Insert cell
Insert cell
stack.map((d,i) => {
d.map(d => {
d.key = keys[i]
return d
})
return d
})
Insert cell
Insert cell
yMax = d3.max(data, d => {
// Is there a better way to do this than calling each key?
var val = 0
for(var k of keys){
val += d[k]
}
return val
})
Insert cell
Insert cell
y = d3.scaleLinear().domain([0, yMax]).range([height,0])
Insert cell
Insert cell
viz = {
// Overall vars
// Set the margin (spacing around the viz)
const margin = 50
// Adjust the height and width to remove the margin
const width = 1000 - margin * 2
// Add the margin back into the SVG and create the SVG wrapper
const svgW = d3.select(DOM.svg(width + margin * 2, height + margin * 2))
// Append a group, which represents the main targetable SVG
const svg = svgW.append('g').attr('transform', `translate(${margin},${margin})`)
// Create some fake data and some scales
var x = d3.scaleLinear().domain([0,data.length]).range([0,width])
var yAxis = d3.axisLeft(y)
// Append some rectangles
svg.selectAll('g')
.data(stack).enter()
.append('g')
.selectAll('rect')
.data(d => d).enter()
.append('rect')
.attr('x', (d,i) => x(i))
.attr('width', width/data.length)
.attr('height', d => {
return y(d[0])-y(d[1])
})
.attr('y', d => y(d[1]))
.attr('fill', d => d.key == 'Births' ? 'lightBlue' : 'orange')
.attr('opacity', .5)
.attr('stroke', 'red')
.attr('stroke-width', 1)

svg.append('g')
.call(yAxis)
return svgW.node()
}
Insert cell
height = 300
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