I created a Series object from my data, like so:
But I don’t know how to actually implement the Series object to scale and bind the data, here is my code:
JavaScript
x
42
42
1
function render(svg) {
2
// const xValue = d => d['Population (2020)'];
3
// const yValue = d => d['Country (or dependency)'];
4
5
// const xExtent = d3.extent(world_population, xValue);
6
// const xScale = d3
7
// .scaleLinear()
8
// .domain(xExtent)
9
// .range([0, width]);
10
11
// const yScale = d3
12
// .scaleBand()
13
// .domain(world_population.map(yValue))
14
// .range([0, height]);
15
16
const xValue = d => d.data;
17
const yValue = d => d.index;
18
19
const xExtent = d3.extent(plot_data.values);
20
const xScale = d3
21
.scaleLinear()
22
.domain(xExtent)
23
.range([0, width]);
24
25
const yScale = d3
26
.scaleBand()
27
.domain(plot_data.index)
28
.range([0, height]);
29
30
const selection = d3.select(svg);
31
selection
32
.selectAll('rect')
33
.data(plot_data)
34
.enter()
35
.append('rect')
36
.attr('fill', 'slateblue')
37
.attr('y', d => yScale(d.index))
38
.attr('width', d => xScale(d.data))
39
.attr('height', yScale.bandwidth());
40
}
41
42
Any help or pointers will be much appreciated.
Advertisement
Answer
The real question here is about your data structure: how to switch to a more convenient one for D3.js purposes?
As you highlighted, we have keys in plot_data.index_arr
, and data in plot_data.data
.
By doing a map
over index_arr
we get the indexes.
The second argument to the callback i
is the index which we can use to get the data, by accessing plot_data.data[i]
.
JavaScript
1
2
1
newData = plot_data.index_arr.map((d,i) => [d, plot_data.data[i]])
2
Once done, we can put them however we want: here I put them in an array, but you can put them in a {key:value} object or a Map object.
JavaScript
1
5
1
plot_data={
2
index_arr:['a',"b", "c"],
3
data:[1,2,3]
4
}
5
console.log(plot_data.index_arr.map((d,i) => [d, plot_data.data[i]]))