Question

I am just starting to learn D3, and have been following a tutorial to create this piece of code.

I created a couple of bars and intend to create an x axis for my graph. The problem is when I add the ".call(xAxis)" to my canvas the browsers won't show me anything and I get the following error in the console:

Uncaught TypeError: Cannot call method 'copy' of undefined d3.min.js:5
(anonymous function) d3.min.js:5
(anonymous function) d3.min.js:3
R d3.min.js:1
da.each d3.min.js:3
n d3.min.js:5
da.call d3.min.js:3
(anonymous function)

Can anyone please help me with what's wrong? I really can't understand what's missing or what I'm doing wrong!

<!doctype html>
<html>
<head>
    <title>Intro to D3</title>
    <script src="d3.min.js"></script>
<head>

<body>
    <script>

        var width = 1024;
        var height = 768;

        var dataArray = [20, 40, 60, 120];

        var xAxis = d3.svg.axis()
        .scale(widthScale);

        var widthScale = d3.scale.linear()
        .domain([0, 120])
        .range([0, width]);

        var color = d3.scale.linear()
        .domain([0, 120])
        .range(["red", "blue"]);

        var canvas = d3.select("body")
        .append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(20, 0)")
        .call(xAxis);

        var bars = canvas.selectAll("rect")
        .data(dataArray)
        .enter()
            .append("rect")
            .attr("width", function(d){ return widthScale(d); })
            .attr("height", 20)
            .attr("fill", function(d){ return color(d); })
            .attr("y", function(d, i){ return i*30; });
    </script>
</body>
</html>
Was it helpful?

Solution

The problem is that you're assigning the scale to the axis before defining it. Doing it in this order works fine:

var widthScale = d3.scale.linear()
    .domain([0, 120])
    .range([0, width]);
var xAxis = d3.svg.axis()
    .scale(widthScale);

You probably also want to append the bars to the SVG itself, not the g element that contains the axis. To do that, simply split the definition of canvas and the appending of the axis:

var canvas = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height);
canvas.append("g")
    .attr("transform", "translate(20, 0)")
    .call(xAxis);

Complete demo here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top