如何在 d3 中的条形图和轴之间添加填充?
How to add padding between bars and axis in d3?
在我的案例中,我想在轴标签和轴线或条形图之间放置图像。现在有点棘手,因为我没有多少space。我受到图形大小的限制,必须使用当前尺寸。我尝试了将 tickPadding()
添加到 y 轴的选项,但这意味着我超过了图形大小并且标签被截断了。有没有办法可以将条形图向右移动?或者把宽度调小一点?
这是我的 y 轴和条形代码:
let yScale_h = d3.scaleBand()
.range([0, height])
.padding(0.2);
let xScale_h = d3.scaleLinear()
.range([0, width]);
let yAxis = d3.axisLeft()
.scale(yScale_h)
.tickSize(0);
svg_bar.selectAll('rect')
.data(dataset_performance, key)
.enter()
.append('rect')
.attr("class", "bar")
.attr('width', function (d) { return xScale_h(d.Award); })
.attr('y', function (d) { return yScale_h(d.clean_test); })
.attr('height', yScale_h.bandwidth())
手动向右偏移条形的一种方法是减小比例范围,并将填充添加到条形的 'x' 属性。
此示例添加 20px 的内边距:
let xScale_h = d3.scaleLinear()
.range([0, width - 20]); // Reduce the range by 20px
...
svg_bar.selectAll('rect')
.data(dataset_performance, key)
.enter()
.append('rect')
.attr("class", "bar")
.attr('x', 20) // Move bars to the right by 20px
.attr('width', function (d) { return xScale_h(d.Award); })
.attr('y', function (d) { return yScale_h(d.clean_test); })
.attr('height', yScale_h.bandwidth())
在我的案例中,我想在轴标签和轴线或条形图之间放置图像。现在有点棘手,因为我没有多少space。我受到图形大小的限制,必须使用当前尺寸。我尝试了将 tickPadding()
添加到 y 轴的选项,但这意味着我超过了图形大小并且标签被截断了。有没有办法可以将条形图向右移动?或者把宽度调小一点?
这是我的 y 轴和条形代码:
let yScale_h = d3.scaleBand()
.range([0, height])
.padding(0.2);
let xScale_h = d3.scaleLinear()
.range([0, width]);
let yAxis = d3.axisLeft()
.scale(yScale_h)
.tickSize(0);
svg_bar.selectAll('rect')
.data(dataset_performance, key)
.enter()
.append('rect')
.attr("class", "bar")
.attr('width', function (d) { return xScale_h(d.Award); })
.attr('y', function (d) { return yScale_h(d.clean_test); })
.attr('height', yScale_h.bandwidth())
手动向右偏移条形的一种方法是减小比例范围,并将填充添加到条形的 'x' 属性。
此示例添加 20px 的内边距:
let xScale_h = d3.scaleLinear()
.range([0, width - 20]); // Reduce the range by 20px
...
svg_bar.selectAll('rect')
.data(dataset_performance, key)
.enter()
.append('rect')
.attr("class", "bar")
.attr('x', 20) // Move bars to the right by 20px
.attr('width', function (d) { return xScale_h(d.Award); })
.attr('y', function (d) { return yScale_h(d.clean_test); })
.attr('height', yScale_h.bandwidth())