Samson Liu
Samson Liu

Reputation: 550

How to import list-like data into d3?

I'm fairly new to D3 and I am having trouble loading and parsing data in a certain way.

I wish I could load some data to my javascript, based on the data itself and the images I wish to generate, it would be awesome if I can load and parse the data in the following fashion:

{field:fieldname, data:[1,2,3,4...]} //an array

I used another python code to generate all the data, and I have tried different ways of writing this information.

For example, I tried to use csv that goes either

field     ,data,data,data,data
fieldnameA,1   ,2   ,3   ,4....
fieldnameB,1   ,2   ,3   ,4....
......

or a transposed version:

fieldnameA, fieldnameB, fieldnameC...
1         , 1         , 1         ...
2         , 2         , 2         ...
...        ...        ...

I couldn't get either to work, and all the other examples I could find go in the format like the following, which is completely different from my goal:

filed     , data    
fieldnameA, 1
fieldnameB, 2
fieldnameC, 3

I was wondering if I can just brutally write my csv as:

field     , data
fieldnameA, [1,2,3,4...]
fieldnameB, [1,2,3,4...]

But then I'm stuck parsing the list in D3...

What would be my best bet here? Should I look into writing to JSON from python? I would really appreciate some help!

Upvotes: 0

Views: 120

Answers (1)

Ian
Ian

Reputation: 34489

The simplest way if you're in control of the source data is to use a JSON format:

[{
    field: "fieldnameA",
    data: [1,2,3,4...],
},{
    field: "fieldnameA",
    data: [1,2,3,4...],
}];

Then you can load the data. D3 can do this in using d3.json just note that this has been changed in the latest V5 version to return a promise instead.

d3.json("myData.json", function(data){

});

Upvotes: 1

Related Questions