Question

I'm trying to create a bar chart with D3.js using JSON data. It seems most of the tutorials use either tsv or csv formats, so i haven't been able to find a suitable answer for my problem.

Problem: I cannot display columns evenly spaced within the chart area using the d3 function rangeBands(...). Instead they appear stacked on top of each other.

I have the following data set:

var jsonData = [
    {"Aluno":"Daniel","Presencas":1,"Media":5,"Cadeira":"A"},
    {"Aluno":"Daniel","Presencas":2,"Media":4,"Cadeira":"B"},
    {"Aluno":"Daniel","Presencas":3,"Media":3,"Cadeira":"C"},
    {"Aluno":"Daniel","Presencas":4,"Media":2,"Cadeira":"D"},
    {"Aluno":"Daniel","Presencas":5,"Media":1,"Cadeira":"E"},
];

...the following scales:

var x = d3.scale.ordinal().rangeRoundBands([0, width], .1);

var y0 = d3.scale.linear().domain([0, 20]).range([height, 0]),
y1 = d3.scale.linear().domain([0, 100]).range([height, 0]);

... and populate the chart the following way:

bars = svg.selectAll(".bar").data(jsonData).enter();
x.domain([0, jsonData.length]);

    bars.append("rect")
      .attr("class", "bar1")
      .attr("x", function(d) { 
          return x(d.Cadeira); 
          })
      .attr("width", x.rangeBand()/2)
      .attr("y", function(d) { 
          return y0(d.Presencas); 
          })
      .attr("height", function(d,i,j) { 
          return height - y0(d.Presencas); 
          }); 

The result is a chart with overlapped columns as shown bellow: enter image description here

I realize (or at least i think i do) that the problem is that I'm applying the scale "x" to each individual data item in jsonData (and not the whole set) like so:

.attr("x", function(d) { 
              return x(d.Cadeira); 
              })

, and hence the columns cant get evenly spaced (because it only spaces 1 element at a time). Is this correct?

How can i correct this?

Thank you for your time.

[Solved]

Solved the problem by correctly adding the domain to "x" thanks to vraiment's answer.

x.domain(jsonData.map(function(d){return d.Cadeira;}));
Was it helpful?

Solution

Maybe you are not initializing the xScale domain (correctly). Something like

x.domain(["A","B","C","D","E"])

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