ttmt
ttmt

Reputation: 4984

D3 - Passing variable to x scale

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.

Upvotes: 0

Views: 132

Answers (1)

aCiD
aCiD

Reputation: 1333

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.

Upvotes: 2

Related Questions