JSFiddle - React, Tailwind, and code Playground
by HemalathaThanigaivel
HTML
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
border: 1px solid red;
}
.bar {
fill: #43c6ac;
}
.bar:hover {
fill: #5cdfc5;
}
.bar:hover {
cursor: pointer;
}
.toolTip {
position: absolute;
display: none;
min-width: 80px;
height: auto;
font-size: 12px;
background: #fff;
border: 1px solid #21c;
padding: 5px;
text-align: center;
}
.toolTip:after {
box-sizing: border-box;
display: inline;
width: 100%;
line-height: 1;
color: #000;
content: "\25BC";
position: absolute;
text-align: center;
margin: -2px 0 0 0;
top: 100%;
left: 0;
}
</style>
<body>
<div id="chart">
</div>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
</script>
</body>
JavaScript
let datajson = [
{
date: "1-Jan-19",
cashTitle: "Cash revenue",
height: 97540.41
},
{
date: "1-Feb-19",
cashTitle: "Cash revenue",
height: 66113.05
},
{
date: "1-Mar-19",
cashTitle: "Cash revenue",
height: 271100.42
},
{
date: "1-Apr-19",
cashTitle: "Cash revenue",
height: 109293.78
},
{
date: "1-May-19",
cashTitle: "Cash revenue",
height: 58037.24
},
{
date: "1-Jun-19",
cashTitle: "Cash revenue",
height: 192681.28
},
{
date: "1-Jul-19",
cashTitle: "Cash revenue",
height: 37172.21
},
{
date: "1-Aug-19",
cashTitle: "Cash revenue",
height: 0
},
{
date: "1-Sep-19",
cashTitle: "Cash revenue",
height: 31985.75
},
{
date: "1-Oct-19",
cashTitle: "Cash revenue",
height: 0
},
{
date: "1-Nov-19",
cashTitle: "Cash revenue",
height: 30967.31
},
{
date: "1-Dec-19",
cashTitle: "Cash revenue",
height: 300000
}
];
let margin = {
top: 20,
left: 50,
right: 20,
bottom: 50
},
width = 1150 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
let svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
let tooltip = d3.select("body").append("div").attr("class", "toolTip");
let xscale = d3.scaleBand()
.domain(datajson.map((d) => {
return d.date;
}))
.range([0, width])
.padding(0.6)
let yscale = d3.scaleLinear()
.domain([0, d3.max(datajson, (d) => {
return d.height;
})])
.range([height, 0])
svg.selectAll(".bar")
.data(datajson)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", (d) => {
return xscale(d.date);
})
.attr("width", xscale.bandwidth())
.on("mousemove", function(d) {
tooltip
.style("left", d3.event.pageX - 50...