Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
Country,Population
chSwitzerland,8000000
deGermany,80000000
United usStates,330000000

Then, create an index.html file with the following content:

Code Block
languagexml
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Barchart</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libsd3js.org/d3/3.5.6/d3.v4.min.js" charset="utf-8"></script>
    <style media="screen">
      body, html {
        height: 100%;
      }
      body {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .list .country {
        background-color: red;
        padding: 10px 10px;
        border-radius: 3px;
        margin: 10px 0;
        color: white;
        font-family: sans-serif;
      }
    </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.linearscaleLinear()
          .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>

Adjust the example to your needs.