简体   繁体   中英

How do I get the width of a bar including padding in d3?

I have an ordinal scale the width of the bar including the padding.

In this case it returns rangeBand returns 29.03 .

var x = d3.scale.ordinal()
    .domain([0, 1, 2])
    .rangeBands([0, 100], 0.1);
console.log(x.rangeBand());

If I have 0 padding it returns 33.33 .

How do I get the width including padding?

For d3.js v4, for a bar graph where you defined your x-scale with something like this:

var x = d3.scaleBand().range([0, n]).padding(0.25).domain( ... )

you get the actual width value of a bar+padding with x.step() and the width value of padding with x.padding() * x.step()

instead of hardcoding pass on the variable. for example

var padding =10;
var width = 100;
var rw = width + padding;

so your code will be

var x = d3.scale.ordinal()
    .domain([0, 1, 2])
    .rangeBands([0, rw ], 0.1);
console.log(x.rangeBand());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM