Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
988 views
in Technique[技术] by (71.8m points)

d3.js - Loading external csv file in jsfiddle

I am trying to create a jsfiddle for one of the dc.js examples. I am not able to load an external file using a URL and d3.csv().

Can someone please suggest how to load a csv file using d3.csv in jsfiddle.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The approach I usually use for CSV data in JSFiddle examples is

a. Put the data in a <pre> block at the end of the HTML mark-up, usually with the id "data".

b. Add pre {display:none;} to the CSS.

c. Replace the d3.csv(filename, callback) function call with a d3.csv.parse(text) call, using the text content of the <pre> block as the input to the parse function.

Because the parse function doesn't use a callback, it just returns the data array, you need to save that output in a variable of the same name as your callback data parameter.

In other words, if your example looks like

d3.csv("data.csv", function(error, data) {

   if(error){console.log("Could not read " + "data.csv");

   /* Do something with `data` here */

});

The JSFiddle-friendly version would look like:

//d3.csv("data.csv", function(error, data) {

//   if(error){console.log("Could not read " + "data.csv");

var data = d3.csv.parse( d3.select("pre#data").text() );

   /* Do something with `data` here */

//});

If you would rather have a full working example that uses the file-reading methods as intended, there are other options as mentioned in the comments. Tributary also allows external data files I think.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...