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
323 views
in Technique[技术] by (71.8m points)

javascript - D3.js scale returning wrong values from dataset

I'm having a problem with scales in d3.js. As I type the min and max into the Firefox console, I get the max value as the min and the second-max value as the max. What's the problem here?

Here is my dataset in form of csv file:

word,occur
obama,11
theguardian,9
world, 8
state, 8
care, 7
pakistan,7
block, 6
blog, 6
healthcare, 5

here is what I type into the console and the values I get in return:

    d3.min(dataset, function(d) { return d.occur}); => "11"
    d3.max(dataset, function(d) { return d.occur}); = "9"

the d3.max should return me 11 and d3.min should return me 5

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You are probably not converting your data from a string to a number. The following should give you the correct answer:

d3.min(dataset, function(d) { return +d.occur}); 
d3.max(dataset, function(d) { return +d.occur});

However, you probably want to convert the occur column of your data to numeric right after reading it:

d3.csv('myfile', function (err, dataset) {     
    dataset.forEach(function (d) { d.occur = +d.occur; });
    // ...
});

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

...