Public
Edited
Jun 28, 2023
Insert cell
Insert cell
Insert cell
{
let bandwidth = plotWidth/(data2.length+1);
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height);

const plot = svg
.append("g")
.attr("transform",`translate(${margin.left},${margin.top})`)

plot.append("line")
.attr("x1",0)
.attr("x2",plotWidth)
.attr("y1",plotHeight-valueScale(0))
.attr("y2",plotHeight-valueScale(0))
.attr("stroke","black")

data2.forEach((d,i)=>{
plot.append("rect")
.attr("x", i * bandwidth)
.attr("y", plotHeight - valueScale(d.negative ? d.start : d.end))
.attr("width", bandwidth/2)
.attr("height", valueScale(Math.abs(d.value)))
.attr("fill", (d.negative ? 'red':'green'))
.attr("stroke-width",1)
.attr("stroke",(d.negative ? 'red':'green'))
.attr("shape-rendering","crispEdges");


plot.append("line")
.attr("x1",i * bandwidth)
.attr("x2",(i+1) * bandwidth)
.attr("y1",plotHeight-valueScale(d.end))
.attr("y2",plotHeight-valueScale(d.end))
.attr("stroke","black")
.attr("stroke-width",1)
.attr("shape-rendering","crispEdges")
console.log("i",i, data2.length-1);
if(i == data2.length-1){
console.log("here");
plot.append("rect")
.attr("x",(i+1) * bandwidth)
.attr("y",plotHeight-valueScale(d.end))
.attr("width",bandwidth/2)
.attr("height",valueScale(d.end))
}
})
return svg.node();
}
Insert cell
Insert cell
Insert cell
height=500
Insert cell
Insert cell
margin = ({
top:20,
bottom:20,
left:20,
right:20
});
Insert cell
Insert cell
plotWidth = width - (margin.left + margin.right);
Insert cell
layout = {
let acc = 0;
return data.map(d=>{
let value = d;
let start = acc;
acc = acc + d;
let end = acc;
let negative = value<0;
return { start, end, value, data:d, negative }
})
}
Insert cell
dataExtent = {
let max;
let min;
data2.forEach((d,i)=>{
if(i==0){
max = Math.max(d.end, d.start);
min = Math.min(d.end, d.start);
}else{
min = d3.min([min, d.end, d.start]);
max = d3.max([max, d.end, d.start]);
}
})
return [min,max];
}
Insert cell
valueScale = d3.scaleLinear()
.domain(dataExtent)
.range([0,plotHeight])
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