pl44
pl44

Reputation: 33

Load json in d3.js

I am trying to create a bar chart. With a .tsv file it works. But now I have to use a .json file. And I don't get it. I tried everything but the site is still blank.

My json file looks like that:

[{"text": "A", "count": 716}, {"text": "B", "count": 359}, {"text": "C", "count": 49}, {"text": "D", "count": 741}, {"text": "E", "count": 130}]

And my code looks like that:

<script src="http://d3js.org/d3.v3.js"></script>

<script>

var margin = {top: 20, right: 30, bottom: 30, left: 430},
    width = 1400 - margin.left - margin.right, 
    height = 500 - margin.top - margin.bottom;

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

var yScale = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(yScale)
    .orient("left")
    .ticks(10, "%");

var svg = d3.select("body")
            .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .attr("class", "chart");

var chart = svg.append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.json("getdata.json", type, function(error,) {
  xScale.domain(data.map(function(d) { return d.text; }));
  yScale.domain([0, d3.max(data, function(d){ return d.count; })]);

  chart.selectAll(".bar")
        .data(data)
        .enter()
        .append("rect")
        .attr("class", "bar")
        .attr("x", function(d) { return xScale(d.text); })
        .attr("y", function(d) { return yScale(d.count); })
        .attr("height", function(d) { return height - yScale(d.count); })
        .attr("width", xScale.rangeBand());

  chart.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  chart.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")
    .text("Value");

});

function type(d) {
  d.count = +d.text; // form d.value by casting frequency to a number
  return d;
}

</script>

Do you have any hints? I guess the json file is wrong or something in the code. For instance d.text could be wrong.

Thank you

Upvotes: 1

Views: 652

Answers (1)

Jan Sch&#228;r
Jan Sch&#228;r

Reputation: 828

d3.json("getdata.json", type, function(error,) {

You forgot something here, it should be:

d3.json("getdata.json", type, function(error, data) {

Also, you have typein this line, which doesn't work with json. It should work if you just remove it:

d3.json("getdata.json", function(error, data) {

But I don't understand what your type function does anyway, if you still need it.

Upvotes: 2

Related Questions