Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

The following example shows a basic usage of d3.js to render a bargraph of country's population.

CSV Data
Country,Population
ch,8000000
de,80000000
us,330000000
HTML Page
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Barchart</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
    <style media="screen">
      .list .country {
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div class="list">
    </div>

    <script type="text/javascript">
      // convert is called with every row in the csv file
      function convert(d) {
        d.Population = parseInt(d.Population);
        return d;
      }

      // load csv and invoke callback with the loaded data
      d3.csv('data.csv', convert, function(data){
        // prepare a scale for the population domain
        var scale = d3.scale.linear()
          .domain([0, d3.max(data, function(d){ return d.Population; })])
          .range([0, 1000]);

        // create a selection of divs with the class country in the div with the class list
        d3.select('.list').selectAll('.country')
          // join with the loaded data
          .data(data)
          // compute set of added rows
          .enter()
            // append a new div to the selection
            .append('div')
              // set class
              .attr('class', 'country')
              // map width of element to population
              .style('width', function(d){
                return scale(d.Population) + 'px';
              })
              // set content to the country's name
              .text(function(d){
                return d.Country;
              });
      });
    </script>
  </body>
</html>