S.GALILEO S.GALILEO - 3 months ago 21
Javascript Question

D3.js Basic Chart Drawing Example not displayed

I am new to Javascript and would like to use the D3 library to visualize my data online.

I have found many examples on the web about drawing a simple bar chart from an array of data. The following example doesn't work however and it just returns a blank web page:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.chart div {
font: 10px sans-serif;
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
}

</style>
<div class="chart"></div>
<script src="http://d3js.org/d3.v4.js"></script>
<script>
var data = [4, 8, 15, 16, 23, 42];

var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, 420]);
d3.select(".chart")
.selectAll("div")
.data(data)
.enter().append("div")
.style("width", function(d) { return x(d) + "px"; })
.text(function(d) { return d; });
</script>


Could this be a problem with the source script (http://d3js.org/d3.v4.js) or maybe the browser?
Any help would be more than appreciated.

Regards.

Answer

You are calling a d3 version 3 method while loading d3 version 4 library. Simply replace:

d3.scale.linear()

With:

d3.scaleLinear()

From the changes docs:

...If you don’t care about modularity, you can mostly ignore this change and keep using the default bundle. However, there is one unavoidable consequence of adopting ES6 modules: every symbol in D3 4.0 now shares a flat namespace rather than the nested one of D3 3.x. For example, d3.scale.linear is now d3.scaleLinear...


Full Code:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
  .chart div {
    font: 10px sans-serif;
    background-color: steelblue;
    text-align: right;
    padding: 3px;
    margin: 1px;
    color: white;
  }
</style>
<div class="chart"></div>
<script src="http://d3js.org/d3.v4.js"></script>
<script>
  var data = [4, 8, 15, 16, 23, 42];

  var x = d3.scaleLinear()
    .domain([0, d3.max(data)])
    .range([0, 420]);
  d3.select(".chart")
    .selectAll("div")
    .data(data)
    .enter().append("div")
    .style("width", function(d) {
      return x(d) + "px";
    })
    .text(function(d) {
      return d;
    });
</script>

Comments