Find the maximum value in a CSV column using d3.max

After using the data (). enter (). append () in D3.js, the individual columns / values ​​in the dataset can be retrieved simply by using d.valuename

. But I want to find the maximum value in the CSV column for the linear scale. Since scale does not undergo any data calls, I really don't know how to specify the correct column from which to find the maximum value.

This is my failed attempt. What can I replace d.column1

with?

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

var x = d3.scale.linear()
    .domain([0, d3.max(d.column1)])
    .range([0, 960]);

      

EDIT:

Ok, I got a little more by looking at a similar example . I don't understand why my code isn't working right now.

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

 data.forEach(function(d) {
    d.column1 = +d.column1;
 });

 var max = d3.max(data, function(d) { return d.column1; });

 var x = d3.scale.linear()
     .domain([0, max])
     .range([0, 960]);

      

EDIT # 2:

In case the problem comes from the data itself, here is a snippet. I tried removing all quotes and also keeping quotes for everything but the top line, but nothing seems to work.

"product", "price"
"bread",20
"meat",100
"meat, sausage",200

      

EDIT # 3:

Okay, I promise one last edit. But just to be absolutely clear; I am using x-scale to determine the width of the bars in the histogram: .attr("width", x)

and the scale returns NaN.

+3


source to share


2 answers


I just figured out what the problem is. No wonder we couldn't figure it out together. All of the above code is fine. It's just that when I called x-scale to determine the width of my bars, I didn't specify which column in the data would be entered into the scale. I had

.attr("width", x)

      

But now I have changed this line to:



.attr("width", function(d) { return x(d.column1); })

      

Thanks for your help and patience.

+1


source


To explain why your code is working:

data.forEach(function(d) {
  d.column1 = +d.column1;
});

      

This operator above converts all of your column values ​​to an integer (the + sign in front of d.column1 forces the type to be a number).



Once your values ​​are all numbers, d3 can now compare them as numbers instead of strings. So 10 will be greater than 9. If they were strings, "9" will be greater than "10".

var max = d3.max(data, function(d) { return d.column1; });

      

The above line just takes the maximum of your data array. Since your dataset consists of objects, d3 has no way of knowing how to compare one object to another. The second parameter is a function that gives d3 a value for each object so that d3 can compare each object. In your case, you are telling d3 to use column1 to determine the maximum value. It's like a comparator function.

+6


source







All Articles