cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - Activehtmlicon-personicon-teamoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External CSS

These stylesheets will be added in this order and before the code you write in the CSS editor. You can also add another Pen here, and it will pull the CSS from it. Try typing "font" or "ribbon" below.

Quick-add: + add another resource

Add External JavaScript

These scripts will run in this order and before the code in the JavaScript editor. You can also link to another Pen here, and it will run the JavaScript from it. Also try typing the name of any popular library.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <div id="container">
  <div id="title"><h1>U.S. Gross Domestic Product</h1></div>
  <svg width="960" height="500" id="chart"></svg>
  <div id="notes"></div>
</div>
<div id="credits">Code by <a href="http://lukewalker.org">Luke Walker</a>, as my solution for <a href="https://www.freecodecamp.com/challenges/visualize-data-with-a-bar-chart">this Free Code Camp project</a>. See all my Data Visualization Projects and notes on <a href="https://ubershibs.github.io/dataviz/">Github</a>.</div>
<div id="projectnotes">
  <h2>Some Notes</h2>
  <p>I found the following resources helpful in constructing this chart:</p>
  <ul>
    <li><strong>IMPORTANT!</strong> <a href="https://iros.github.io/d3-v4-whats-new/#1">This slideshow</a> was very helpful when it came to understanding the many differences (breaking diffs) between v3 and v4 of d3. Most of the tutorials on the d3 site are still written for v3 and won't work if you use the v4 library.</li>
    <li><a href="https://bl.ocks.org/mbostock/3885304">A sample v4 bar chart</a></li>
    <li><a href="https://bl.ocks.org/alandunning/274bf248fd0f362d64674920e85c1eb7">A sample barchart with tooltips</a></li>
    <li><a href="http://stackoverflow.com/questions/36999574/d3v4-time-scale-axis-error-in-ticks-display">This Stack Overflow question</a> helped me sort out how to make the labels on the x axis work in v4 as they do on the sample chart.</li>
  </ul>
</div>
            
          
!
            
              body {
  background-color: lightgray;
}

#container {
  background-color: white;
}

#chart text {
  fill: black;
  font: 10px sans-serif;
  text-anchor: end;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}
.axis text {
  font: 10px sans-serif;
}

.bar { 
  fill: steelblue; 
}

.mouseover {
  fill: lightgray;
}

.tooltip {
  position: absolute;
  text-align: center;
  width: 140px;
  height: 40px;
  padding: 10px 5px;
  font: 16px sans-serif;
  background: lightsteelblue;
  border: 0px;
  border-radius: 8px;
  display: none;
  opacity: 0.8;
}

.date, .dollars {
  display: block;
  padding-bottom: 5px;
}

.date {
  font-weight: 700;
}

#notes {
  font-family: sans-serif;
  font-size: 12px;
  text-align: center;
}

#container {
  border: 1px solid black;
  width: 960px;
  height: 600px;
  margin: 10px auto;
  padding: 10px 30px;
}

#chart {
  margin : 20px;
}

#title {
  width: 100%;
}

#title h1 {
  font-family: sans-serif;
  font-size: 30px;
  text-align: center;
  color: steelblue;
}

#projectnotes {
  width: 960px;
  margin: 10px auto;
  font-size: 14px;
  font-family: sans-serif;
}

#projectnotes h2 {
  color: steelblue;
  font-size: 18px;
}
#projectnotes ul {
  list-style: disc outside none;
  margin: 10px 50px;
}

#projectnotes li {
    line-height: 1.3;
}

#credits {
  font-family: sans-serif;
  font-size: 14px;
  width: 960px;
  text-align: center;
  margin: 20px auto;
  border: 1px solid black;
  padding: 5px;
  background-color: white;
}
            
          
!
            
              var dataURL = 'https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json',
    months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    formatBillions = d3.format("$,.1f");

  var tooltip = d3.select('body').append("div").attr("class", "tooltip");

$.get(dataURL, function(response, status) {
  
  var svg = d3.select("svg"),
      margin = {top: 20, right: 20, bottom: 40, left: 40},
      width = +svg.attr("width") - margin.left - margin.right,
      height = +svg.attr("height") - margin.top - margin.bottom;

  var x = d3.scaleTime().range([0, width]),
      y = d3.scaleLinear().rangeRound([height, 0]);

  var g = svg.append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var responseJSON = JSON.parse(response); 
    
  d3.select('#notes')
    .append('text')
    .text(responseJSON.description);   
  
  var dataArr  = responseJSON.data;  
  var data =[];

  dataArr.forEach(function(d) {
    var obj = {};
    obj.date = new Date(d[0]);
    obj.gdp = d[1];
    data.push(obj);
  });
  
  var chartWidth = Math.ceil(width / data.length);
  var dateA = data[0].date;
  var dateZ = data[data.length - 1].date;
  
  x.domain([dateA, dateZ]);
  y.domain([0, d3.max(data, function(d) { return d.gdp; })]);

  g.append("g")
      .attr("class", "axis axis--x")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x).ticks(d3.timeYear, 5).tickFormat(d3.timeFormat("%Y")).tickSizeOuter(0))
      .selectAll("text")  
        .style("text-anchor", "end")
        .attr("dx", "-.8em")
        .attr("dy", ".15em")
        .attr("transform", "rotate(-65)" );
  
  g.append("g")
      .attr("class", "axis axis--y")
      .call(d3.axisLeft(y).ticks(10).tickSizeOuter(0))
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", "0.71em")
      .attr("text-anchor", "end")
      .text("U.S Gross Domestic Product (in Billions of $)");

  g.selectAll(".bar")
    .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.date); })
      .attr("y", function(d) { return y(d.gdp); })
      .attr("width", chartWidth)
      .attr("height", function(d) { return height - y(d.gdp); })
      .on("mouseover", showTip)
      .on("mouseout", hideTip);
});

function showTip(d) {
  var bar = d3.select(this);
  bar.attr("class", "mouseover");
  var year = d.date.getFullYear();
  var month = d.date.getMonth();
  tooltip.html('<span class="date">' + months[month] + ' ' + year + '</span><span class="dollars">' + formatBillions(d.gdp) + ' billion</span>')
  .style('left', (d3.event.pageX + 10) + 'px')
  .style('top', (d3.event.pageY + 10) + 'px')
  .style('display', 'block');
}

function hideTip(d) {
  var bar = d3.select(this);
  bar.attr('class', 'bar')
  tooltip.style('display', 'none');
}
            
          
!
999px
Close

Asset uploading is a PRO feature.

As a PRO member, you can drag-and-drop upload files here to use as resources. Images, Libraries, JSON data... anything you want. You can even edit them anytime, like any other code on CodePen.

Go PRO

Loading ..................

Console