D3JS:无法在x轴上仅设置5个刻度

时间:2018-10-25 23:34:20

标签: d3.js

我一直无法在我的x轴上设置5个刻度,默认情况下它设置了10个刻度,是5的倍数,我尝试使用“ .ticks(5)”,但它对我不起作用。如果在移动设备上可视化图表,则10个刻度几乎不可读。但是正如我提到的“ .ticks(5)”那样,它不起作用

这是绘制x轴的代码段:

 var xAxis = svg.append("g")
                .style("font-size", textSetter())
                .attr("class", "xAxis", "axis")
                .attr("transform", "translate(" + 0 + "," + heightTwo + ")")
                .call(d3.axisBottom(xScale).ticks(5)
               .tickPadding(5).tickFormat(d => d + "%"))

我该如何解决?谢谢

1 个答案:

答案 0 :(得分:1)

您可以将轴中的所有文本设置为特定的类,然后例如基于数字隐藏刻度线。

//Create the xAxis and assign x-axisticks class to the tick text
var xAxis = svg.append("g")
                .style("font-size", textSetter())
                .attr("class", "xAxis", "axis")
                .attr("transform", "translate(" + 0 + "," + heightTwo + ")")
                .call(d3.axisBottom(xScale)
                .selectAll('text')
                .attr('class', 'x-axisticks');

//remove the ticks which based on the multiples      
var xticks = d3.selectAll('.x-axisticks');
xticks.attr('class', function (d, i) {
      i = i + 1;
      if (i % 5 !== 0) d3.select(this).remove();
   });

希望这会有所帮助。一个更具体的用例答案可能需要在您的末尾发布更多代码,以便我可以定制答案,但这应该可行。

相关问题