JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>United States GDP visualization</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<main>
<div id="title">
<h1>United States GDP</h1>
<h2>freeCodeCamp - Visualize Data with a Bar Chart Project</h2>
</div>
</main>
<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
CSS
@import url('https://fonts.googleapis.com/css?family=Ubuntu+Mono');
body {
margin: 0;
padding: 0;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
background-color: #888;
font-family: 'Ubuntu Mono', monospace;
color: #fff;
}
main {
width: 100%;
text-align: center;
}
svg {
background-color: #eee;
}
.bar:hover {
fill: #fff;
}
#tooltip {
visibility: hidden;
font-weight: bold;
color: #00f;
background-color: #99e6ff;
display: inline-block;
padding: 10px;
border-radius: 5px;
position: absolute;
}
JavaScript
/* global d3 */
(function() {
'use strict';
const url = 'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json';
d3.json(url).then(function(data) {
const dataset = data.data;
const w = 900;
const h = 500;
const padding = 50;
const barWidth = (w - 2 * padding) / dataset.length;
// scale the data for the axes
const minYear = d3.min(dataset, (d) => d[0]);
const maxYear = d3.max(dataset, (d) => d[0]);
const xScale =
d3.scaleTime()
.domain([new Date(minYear), new Date(maxYear)])
.range([padding, w - padding]);
const yScale =
d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[1])])
.range([h - padding, padding]);
// create canvas div for svg and tooltip
d3.select('body')
.append('div')
.attr('id', 'canvas')
.attr('width', w)
.attr('height', h);
// create svg element and append it to body
const svg =
d3.select('#canvas')
.append('svg')
.attr('width', w)
.attr('height', h);
// add tooltip div
const tooltip =
d3.select('#canvas')
.append('div')
.attr('id', 'tooltip');
// add bars to the graph
svg.selectAll('rect')
.data(dataset)
.enter()
.append('rect')
.attr('class', 'bar')
.attr('x', (d, i) => i * barWidth)
.attr('y', (d) => yScale(d[1]))
.attr('width', barWidth)
.attr('height', (d) => h - padding - yScale(d[1]))
.attr('transform', 'translate(' + padding + ',0)')
.attr('fill', '#00f')
.attr('data-date', (d) => d[0])
.attr('data-gdp', (d) => d[1])
.on('mouseover', (d) => {
tooltip.attr('data-date', d[0])
.html(showTooltip(d[0], d[1]))
.style('top',(d3.event.pageY - 80) + 'px')
.style('left', (d3.event.pageX) + 'px')
.style('visibility', 'visible');
})
.on('mouseout', () => {
...