Bar Chart (D3)

In this example below you will see how to do a Bar Chart (D3) with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by Gouldie, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Gouldie ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Bar Chart (D3)</title>
  
  
  <link rel='stylesheet prefetch' href='https://fonts.googleapis.com/css?family=Josefin+Sans'>

      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div class="container">
  
  <div class="root">
    <h1>Gross Domestic Product</h1>
    <div class="chart"></div>
    <p class="textBottom">Units: Billions of Dollars Seasonal Adjustment: Seasonally Adjusted Annual Rate Notes: A Guide to the National Income and Product Accounts of the United States (NIPA) - (http://www.bea.gov/national/pdf/nipaguid.pdf)</p>
  </div>
  
</div>

<div class="tooltip hidden">
  <p><strong id="gdp"></strong></p>
  <p id="date"></p>
</div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/axios/0.14.0/axios.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/Gouldie/bar-chart-d3-ORRYzd */
body {
  background: url(https://i1376.photobucket.com/albums/ah2/christopher_marro1/graphy_zpsxj4velkt.png);
  font-family: 'Josefin Sans', sans-serif;
}

.container {
  display: flex;
  justify-content: center;
}

.root {
  margin-top: 100px;
  border: 1px solid black;
  width: 1000px;
  background-color: white;
  -webkit-box-shadow: 4px 4px 10px 2px rgba(0,0,0,0.5);
  -moz-box-shadow: 4px 4px 10px 2px rgba(0,0,0,0.5);
  box-shadow: 4px 4px 10px 2px rgba(0,0,0,0.5);
}

.axis path,
.axis line {
    fill: none;
    stroke: black;
    shape-rendering: crispEdges;
}

.axis text {
    font-family: sans-serif;
    font-size: 11px;
}

h1 {
  text-align: center;
  color: steelblue;
}

.tooltip {
  position: absolute;
  background: gray;
  color: white;
  border-radius: 5px;
  top: 500px;
  left: 100px;
  z-index: 98;
  width: 140px;
  height: 50px;
  -webkit-box-shadow: 4px 4px 10px 2px rgba(0,0,0,0.5);
  -moz-box-shadow: 4px 4px 10px 2px rgba(0,0,0,0.5);
  box-shadow: 4px 4px 10px 2px rgba(0,0,0,0.5);
}

.hidden {
  display: none;
}

p {
  text-align: center;
  margin: 2px 0;
}

.textBottom {
  margin-bottom: 15px;
  color: steelblue;
}



/*Downloaded from https://www.codeseek.co/Gouldie/bar-chart-d3-ORRYzd */
console.clear();

const url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json";

d3.json(url, (response) => {
  let data = [];
  let w = 1000;
  let h = 500;
  let edgePadding = 50;
  
  for (let i = 0; i < response.data.length; i++) {
    let date = new Date(response.data[i][0]);
    var formatMonth = d3.timeFormat("%B")
    var formatYear = d3.timeFormat("%Y");
    var year = formatYear(date);
    var month = formatMonth(date);
    var obj = {
      y: year,
      m: month,
      full: date,
      value: response.data[i][1]
    }
    data.push(obj);
  }
  
  var xScale = d3.scaleBand()
    .domain(d3.range(data.length))
    .range([0, w - edgePadding * 2]);
  
  var xAxisScale = d3.scaleTime()
    .domain([d3.min(data, function(d) {
      return d.full;
    }), d3.max(data, function(d) {
      return d.full;
    })])
    .range([0, w - edgePadding * 2]);
  
  var yScale = d3.scaleLinear()
    .domain([0, d3.max(data, function(d) { return d.value; })])
    .range([0, h - edgePadding * 2]);
  
  var yAxisScale = d3.scaleLinear()
    .domain([d3.max(data, function(d) { return d.value; }), 0])
    .range([0, h - edgePadding * 2]);
  
  var svg = d3.select(".chart")
              .append("svg")
              .attr("width", w)
              .attr("height", h);
  
  svg.selectAll("rect")
      .data(data)
      .enter()
      .append("rect")
      .attr("x", (d, i) => {
        return xScale(i) + edgePadding;
      })
      .attr("y", (d) => {
        return h - yScale(d.value) - edgePadding;
      })
      .attr("width", w / data.length)
      .attr("height", (d) => {
        return yScale(d.value);
      })
      .attr("fill", "steelblue")
      .on("mouseover", function(d){
        $(this).stop()
               .css({'fill': 'transparent'});
    
        var xMousePos = d3.event.x;
        var yMousePos = d3.event.y;
        var formattedValue = d.value.toLocaleString('en-US', {minimumFractionDigits: 2});
        var gdp = "$" + formattedValue + " Billion";
        var date = d.y + " - " + d.m;
    
        d3.select(".tooltip").style("left", xMousePos + 10 + "px")
                             .style("top", yMousePos - 50 + "px");
        d3.select("#gdp").text(gdp);
        d3.select("#date").text(date);
        d3.select(".tooltip").classed("hidden", false);

      })
      .on("mouseout", function(){
        $(this).stop()
               .css({'fill': 'steelblue'});
        d3.select(".tooltip").classed("hidden", true);
      });
     
  
  var xAxis = d3.axisBottom()
    .scale(xAxisScale)
    .ticks(d3.timeYear.every(5));
  
  var yAxis = d3.axisLeft()
    .scale(yAxisScale);
  
  svg.append("g")
     .attr("class", "axis")
     .attr("transform", "translate(" + edgePadding + "," + (h - edgePadding) + ")")
     .call(xAxis);
  
   svg.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(" + edgePadding + "," + edgePadding + ")")
    .call(yAxis);
  
  svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", edgePadding + 20)
    .attr("x", -15)
    .attr("transform", "rotate(-90)")
    .text("Gross Domestic Product, USA");
});

Comments