JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<head><title>Bar Graph</title></head>
<link rel="stylesheet" href="app.css">
<body>
<div id="container">
<div>
<div id="title">United States GDP</div>
<div class="graph"></div>
</div>
</div>
</body>
<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<script src="temp.js"></script>
<script src="app.js"></script>
</html>
CSS
#container
{
margin: 0 auto;
height:600px;
width: 1000px;
border: 2px solid black;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.graph
{
height:500px;
width: 1000px;
display: flex;
align-items: center;
justify-content: center;
}
rect:hover
{
fill: #454545;
}
#tooltip
{
opacity: 0;
position: absolute;
pointer-events: none;
background-color: rgba(223,234,245,0.8);
border-radius: 5px;
padding: 15px;
font-size: 14px;
line-height: 2px;
box-shadow: 2px 2px 1px 1px #454545;
min-width: 100px;
}
#title
{
text-align: center;
font-size: 30px;
}
JavaScript
url ="https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json";
d3.json(url,function(err,dataset){
barGraph(dataset)});
var barGraph=function(dataset){
const width = 800;
const height = 400;
const padding =40;
const heightMod = 350 -padding;
const widthMod= 700 -padding;
var i=0;
var barInfo=[];
var margin={
top:20,
bottom:20,
left:20,
right:20
}
var tooltip = d3.select("body")
.append("div")
.attr("id","tooltip");
format = d3.timeFormat("%x");
while(i<dataset.data.length)
{
date =new Date(dataset.data[i][0]);
year = date.getFullYear();
value=dataset.data[i][1];
barInfo.push({
"date":date,
"value":value
})
i++;
}
// ===========================================
// D3 ahead
// ===========================================
barCount=Object.keys(barInfo).length;
// Scaling the values
svg=d3.select(".graph")
.append("svg")
.attr("width",width)
.attr("height",height)
.style("padding-left",padding+"px")
.style("padding-top",padding+"px");
const maxDate = d3.max(barInfo,(d) => d.date);
const minDate = d3.min(barInfo,(d) => d.date);
scaleX = d3.scaleTime()
.domain([minDate,maxDate])
.range([padding,widthMod]);
const maxValue = d3.max(barInfo,(d) => d.value);
const minValue = d3.min(barInfo,(d) => d.value);
scaleY = d3.scaleLinear()
.domain([minValue,maxValue])
.range([heightMod,heightMod*(minValue/maxValue)]);
//Adding Axes
const xAxis = d3.axisBottom(scaleX);
svg.append("g")
.attr("id","x-axis")
.attr("transform","translate(0,"+heightMod+")")
.call(xAxis);
const yAxis = d3.axisLeft(scaleY);
svg.append("g")
.attr("id","y-axis")
.attr("transform","translate("+padding+",0)")
.call(yAxis);
//Plotting graph
rect=svg.selectAll("rect")
.data(barInfo)
.enter()
.append("rect")
...