JSFiddle - React, Tailwind, and code Playground
by gdicerbo
HTML
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="960" height="500"></svg>
CSS
.line {
fill: none;
stroke: black;
stroke-width: 1.2px;
}
JavaScript
var data = [
{month: "2018", CapEx: -14202756, Revenue: 0, OpEx: 0, Depreciation: 0},
{month: "2019", CapEx: 0, Revenue: 2242378, OpEx: -515070, Depreciation: 3700753},
{month: "2020", CapEx: 0, Revenue: 4168212, OpEx: -704541, Depreciation: 8405422},
{month: "2021", CapEx: 0, Revenue: 4244142, OpEx: -720288, Depreciation: 7679068}
];
var series = d3.stack()
.keys(["CapEx", "Revenue", "OpEx", "Depreciation"])
.offset(d3.stackOffsetDiverging)
(data);
var svg = d3.select("svg"),
margin = {top: 20, right: 30, bottom: 30, left: 60},
width = +svg.attr("width"),
height = +svg.attr("height");
var x = d3.scaleBand()
.domain(data.map(function(d) { return d.month; }))
.rangeRound([margin.left, width - margin.right])
.padding(0.1);
var y = d3.scaleLinear()
.domain([d3.min(series, stackMin), d3.max(series, stackMax)])
.rangeRound([height - margin.bottom, margin.top]);
var z = d3.scaleOrdinal(d3.schemeCategory20c);
svg.append("g")
.selectAll("g")
.data(series)
.enter().append("g")
.attr("fill", function(d) { return z(d.key); })
.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("width", x.bandwidth)
.on("mouseover", function() { tooltip.style("display", null); })
.on("mouseout", function() { tooltip.style("display", "none"); })
.on("mousemove", function(d) {
console.log(d);
var xPosition = d3.mouse(this)[0] - 5;
var yPosition = d3.mouse(this)[1] - 5;
tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
tooltip.select("text").text(d[1]-d[0]);})
.attr("x", function(d) { return x(d.data.month); })
.attr("y", function(d) { return y(d[1]); })
.attr("height", function(d) { return y(d[0]) - y(d[1]); })
svg.append("g")
.attr("transform", "translate(0," + y(0) + ")")
.call(d3.axisBottom(x));
svg.append("g")
.attr("transform", "translate(" + margin.left + ",0)")
...