问题描述
我根据自己的数据创建了一个Series对象,如下所示:
但是我不知道如何实际实现Series对象来缩放和绑定数据,这是我的代码:
function render(svg) {
// const xValue = d => d['Population (2020)'];
// const yValue = d => d['Country (or dependency)'];
// const xExtent = d3.extent(world_population,xValue);
// const xScale = d3
// .scaleLinear()
// .domain(xExtent)
// .range([0,width]);
// const yScale = d3
// .scaleBand()
// .domain(world_population.map(yValue))
// .range([0,height]);
const xValue = d => d.data;
const yValue = d => d.index;
const xExtent = d3.extent(plot_data.values);
const xScale = d3
.scaleLinear()
.domain(xExtent)
.range([0,width]);
const yScale = d3
.scaleBand()
.domain(plot_data.index)
.range([0,height]);
const selection = d3.select(svg);
selection
.selectAll('rect')
.data(plot_data)
.enter()
.append('rect')
.attr('fill','slateblue')
.attr('y',d => yScale(d.index))
.attr('width',d => xScale(d.data))
.attr('height',yScale.bandwidth());
}
任何帮助或指针将不胜感激。
解决方法
这里真正的问题是关于您的数据结构:如何出于D3.js的目的切换到更方便的数据结构?
正如您强调的那样,我们在plot_data.index_arr
中有密钥,在plot_data.data
中有数据。
通过在map
上进行index_arr
,我们得到了索引。
回调i
的第二个参数是索引,我们可以通过访问plot_data.data[i]
来获取数据。
newData = plot_data.index_arr.map((d,i) => [d,plot_data.data[i]])
完成后,我们可以根据需要放置它们:在这里我将它们放置在数组中,但是您可以将它们放置在{key:value}对象或Map object中。
plot_data={
index_arr:['a',"b","c"],data:[1,2,3]
}
console.log(plot_data.index_arr.map((d,plot_data.data[i]]))