D3 - Passing variable to x scale

不羁岁月 提交于 2019-12-24 21:14:52

问题


I have a codepen here - https://codepen.io/anon/pen/yvgJKB

I have a simple stacked bar chart.

I want to make this into a component so I need to pass in the values to make it reuseable

The x scale function returns d.date

let x = d3.scaleBand()
    .domain(dataToStack.map(function(d){
        return d.date;
    }))
    .rangeRound([0,width])
    .padding(0.05);

I want to pass the 'date' part in from a variable

I can do this for the x attr of the bar.

let xAxisValue = 'date'

.attr('x', (d, i) => {
    let link = d.data[xAxisValue];                         
    return x(link)
})

I also need to pass this into the x scale

let x = d3.scaleBand()
    .domain(dataToStack.map(function(d){
        //let link = d.[xAxisValue];                         
        //return x(link)
        return d.date;
    }))
    .rangeRound([0,width])
    .padding(0.05);

The same square brackets dont work here.

How can I pass in the xAxisValue to the x scale function.


回答1:


let xAxisValue = 'date';

in line 1 to make the codepen sample working.

And then

let x = d3.scaleBand()
.domain(dataToStack.map(function(d){
    let link = d[xAxisValue];                         
    return link;
    //return d.date;
}))
.rangeRound([0,width])
.padding(0.05);

It works when I modify it in your codepen sample.



来源:https://stackoverflow.com/questions/48736188/d3-passing-variable-to-x-scale

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!