0

I'm trying to create a bar chart using the json url. With respect to impressions and time. I don't think I'm referencing the data correctly at .data(data) how do I access the impressions field from json file in d3?

var url = "https://script.google.com/macros/s/AKfycbwy56QiQwyfkkaLFWZ33QHVieAHhtLJYNa_AzKcCBr-J7Catgv2/exec?id=1vQsWQPUET20KcgeRKgs5NOOBngqLeUuNTHI1bWi5Et8&sheet=Sheet1";


d3.json(url, function(data) {
    console.log(data.Sheet1[0]);

    var canvas = d3.select("body").append("svg")
        .attr("width", 500)
        .attr("height", 500)
    canvas.selectAll("rect")
        .data(data)
        .enter()
        .append("rect")
        .attr("width", function(d) {
            return d.Impressions
        })
        .attr("height", 45)
        .attr("y", function(d, i) {
            return i * 50
        })
        .attr("fill", "blue")
});
1
  • Try data.Sheet1
    – Weedoze
    Commented Oct 24, 2016 at 12:27

1 Answer 1

1

You have to pass an array to the function data(). Thus, since data is an object:

Object {Sheet1: Array[71]}

Your data should be data.Sheet1 instead. Check the demo:

var url = "https://script.google.com/macros/s/AKfycbwy56QiQwyfkkaLFWZ33QHVieAHhtLJYNa_AzKcCBr-J7Catgv2/exec?id=1vQsWQPUET20KcgeRKgs5NOOBngqLeUuNTHI1bWi5Et8&sheet=Sheet1";

d3.json(url, function (data) {

var scale = d3.scale.linear()
    .domain([0, d3.max(data.Sheet1, function(d){ return d.Impressions})])
    .range([0, 500]);


var canvas = d3.select("body").append("svg")
    .attr("width",500)
    .attr("height",500)
canvas.selectAll("rect")
    .data(data.Sheet1)
    .enter()
        .append("rect")
        .attr("width",function(d){return scale(d.Impressions)})
        .attr("height", 6)
        .attr("y",function(d,i){return i*7})
        .attr("fill","blue")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

PS: I added a scale to your code.

Not the answer you're looking for? Browse other questions tagged or ask your own question.