Home Ask Login Register

Developers Planet

Your answer is one click away!

Shoplifter20 February 2016

How to display an array on text using d3?

I am using the Gridster library, and I have a Gridster box created:

<li data-sizey="2" data-sizex="2" data-col="3" data-row="1">
    <div class="gridster-box" id="box1">
        <div class="handle-resize"></div>
    </div>
</li>

In my JS file I call a JSON response from my back-end

function createGraph() {
    d3.json("/hours", function (data){
        // Stuff here
    }
}

The response, as shown in the console of the browser, is

Object {initial_hours: Array[19]}
initial_hours: Array[19]

Where the array contains:

0: 1800
1: 1700
2: 1030
3: 1130
4: 950
5: 1249
6: 1225
7: 1821
8: 1250
9: 1505
10: 38
11: 130
12: 1520
13: 1600
14: 1330
15: 1930
16: 1806
17: 1535
18: 1855
length: 19

How do I print this array as a text in my Gridster box?

Answers


WittyID February 2016

Your problem seems to primarily be a d3 problem, i.e. binding an array of data to some DOM element. Below is a mock of your json data and how you can append its data to the DOM.

I've broken array data list into 3 columns but you can play around with that by adjusting the x and y functions.

var svg = d3.select("svg");

var jsonResObj = {
               initial_hours: [
                  1800, 1700, 1030, 1130, 950, 1249, 1225, 1821, 1250,
                  1505, 38, 130, 1520, 1600, 1330, 1930, 1806, 1535
                ]
              };

var text = svg.selectAll('text')
    .data(jsonResObj.initial_hours)
   .enter().append('text')
    .attr("x", function(d,i){return 100 * (i % 3)})
    .attr("y", function(d,i){return 20 * ( Math.floor(i/3) ) })
    .attr("fill", "#000")
    .text(function(d){return d});

You should be able to do the same for gridster by selecting using the id or class e.g.

var svg = d3.select("#box1");

Here's a fiddle of the above.

Post Status

Asked in February 2016
Viewed 1,065 times
Voted 10
Answered 1 times

Search




Leave an answer


Quote of the day: live life