Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  142] [ 7]  / answers: 1 / hits: 15646  / 11 Years ago, fri, march 29, 2013, 12:00:00

I'm making an interactive bar chart in d3, and have come across a problem. The bar chart reads data from a form, but it reads the data as a string. When I am using the data to draw bars like this:



var bars = svg.selectAll(rect)
.data(dataset)
.enter()
.append(rect)
.attr(x, function(d,i) {
return i * (w / dataset.length);
})
.attr(y, function(d) {
return h - (d * 4);
})
.attr(width, w / dataset.length - barPadding)
.attr(height, function(d) {
return d * 4;
})
.attr(fill, function(d) {
return rgb( + (d * redLevel) + , 0, + (d * blueLevel) + );
});


the data is read as a string. I could use parseInt(d) every time I wanted to use d, but that would be grossly inefficient. It would be easy to do var d = parseInt(d) outside of the method chain, but that wouldn't work with d3. Suggestions?


More From » d3.js

 Answers
28

You could map the data before you bind it:



.data(dataset.map(function(d) { return +d; }))


Then unary + operator converts a numeric string into a number.


[#79242] Thursday, March 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andreguym

Total Points: 125
Total Questions: 112
Total Answers: 103

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;