I'm trying to create a D3 chart that will utilize both summary statistics (min and max) as well as unsummarized data.
I have a CSV that contains a Job Code (which contains duplicates) and a salaryToMedian which is a decimal. I want to compute the min and max by Job Code.
I'm receiving the error grouped is not a function
. I'm trying to console.log the maximum for Job Code 1000.
d3.csv("http://127.0.0.1:8887/myData.csv").then(function(data){
var grouped = d3.nest()
.key(function(d) { return d.jobCode; })
.rollup(function(v) {
return {
jobCodeMax: d3.max(v, function(d) { return d.salaryToMedian; }),
jobCodeMax: d3.min(v, function(d) { return d.salaryToMedian; }),
values: v
};
})
.entries(data)
.map(function(d) {
return {
JobCode: d.key,
jobCodeMax: d.value.jobCodeMax,
jobCodeMin: d.value.jobCodeMin
};
});
console.log(grouped(1000).jobCodeMax);
});
CodePudding user response:
Disclaimer: At the time of writing, the current version of d3 is version 7.6.1.
map
returns an array, but you try to access it like a function, i.e., with parentheses.
Also: d3.nest has been deprecated in d3 version 6, which is also stated in the docs:
Deprecation notice: Use JavaScript’s built-in Map, Set and Object classes instead of d3-collection’s corresponding methods. Use d3-array’s group and rollup instead of d3-collection’s nest.
But: No need for all those calls. All you need is d3.rollup
.
d3.rollup(iterable, reduce, ...keys)
Groups and reduces the specified iterable of values into an InternMap from key to value.
This should do the trick (once you have stored your data in the variable data
):
// ... get data into variable data ...
const keyFn = d => d.jobCode
const valueFn = d => d.salaryToMedian
const summaryReducer = function(values) {
return {
key: keyFn(values[0]), // if you want to also store the key in the summary
max: d3.max(values, valueFn),
min: d3.min(values, valueFn),
/* any other summarization you want based on values */
values: values
}
}
const grouped = d3.rollup(data, summaryReducer, keyFn) // all you need is d3.rollup
const job1000 = grouped.get(1000)
I created a playground example here on ObeservableHQ.