Public
Edited
Aug 29, 2023
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 = 500 - 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', 150)
.attr('height', d => {
return y(d[0])-y(d[1])
})
.attr('y', d => y(d[1]))
// .attr('fill', d => d.key == 'ED Visits' ? 'lightBlue' : 'orange')
.attr('fill', d => {
if (d.key == 'ED Visits') { return '#4aac66'}
else if (d.key == 'Hospitalizations') { return '#73bd83'}
else if (d.key == 'Ambulance and Nalaxone Use') { return '#97cea1'}
else {return "#0b8040"};
})
// .attr('opacity', d => d.key == 'Other' ? 1 : 0.85)
.attr('stroke', 'white')
.attr('stroke-width', 1)

// svg.append('g')
// .call(yAxis)
return svgW.node()
}
Insert cell
data = [
{
"Type": "Indirect",
"ED Visits": 0,
"Hospitalizations": 0,
"Ambulance and Nalaxone Use": 0,
"Other": 812584286
},
{
"Type": "Direct",
"ED Visits": 35368489,
"Hospitalizations": 203024598,
"Ambulance and Nalaxone Use": 16091701,
"Other": 0
}
]
Insert cell
keys = Object.keys(data[0]).slice(1)
Insert cell
stack = d3.stack().keys(keys)(data)
Insert cell
stack.map((d,i) => {
d.map(d => {
d.key = keys[i]
return d
})
return d
})
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
y = d3.scaleLinear().domain([0, yMax]).range([height,0])
Insert cell
height = 300
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more