如何解决D3柱状图X轴标签被viewbox截断的问题?
D3.js柱状图X轴标签因viewBox尺寸被截断的问题与解决方法
问题描述
在div容器内使用viewBox绘制D3柱状图时,X轴标签无法适配viewBox尺寸,出现截断情况,仅在Chrome开发者控制台调大viewBox高度后,标签才能完整显示。
原代码
JavaScript代码
const width = 1152; const height = 700; const marginTop = 100; const marginRight = 0; const marginBottom = 30; const marginLeft = 100; var svg = d3.select("#divAccesos") .append("svg") .attr("viewBox", [0, 0, width, height]); // Add axes svg.append("g") .attr("class", "x axis") .attr("transform", `translate(0,${height - marginBottom})`) .call(d3.axisBottom(xScale)) .selectAll("text") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("font-size", "1.6em") .attr("transform", "rotate(-65)");
HTML容器代码
<div id="divAccesos" align="center" style="position:relative; width:80%; overflow: visible; padding-top:4vh; height: 900px;"> </div>
问题原因
X轴标签设置了65度旋转,且字体大小为1.6em,需要额外的垂直空间才能完整显示,但原代码中marginBottom仅设置为30,预留空间不足,导致标签超出viewBox的可视范围被截断。
解决方案
保持viewBox的height值不变,增大marginBottom以预留足够的X轴标签空间,调整后的代码如下:
const width = 1152; const height = 600; const marginTop = 100; const marginRight = 0; const marginBottom = 200; // 原数值为30 const marginLeft = 100;
内容的提问来源于stack exchange,提问作者david9ppo
相关产品推荐
相关产品推荐

