如何使用d3.js在X轴上添加间隔?

时间:2017-12-19 12:41:57

标签: javascript d3.js

我希望得到10的间隔,从0开始直到50.但我得到间隔为5.

这是代码

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.12/d3.min.js"></script>
</head>
<body>
    <script>
        var xAxis = d3.svg.axis();
        var axisScale = d3.scale.linear()
                   .domain([0,100])
                   .range([0,100]);
        var xAxis = d3.svg.axis()
                      .scale(axisScale);
        typeof(xAxis);
        var svgContainer = d3.select("body").append("svg")
                                  .attr("width", 700)
                                  .attr("height", 100);

        //Create the Scale we will use for the Axis
        var axisScale = d3.scale.linear()
                      .domain([0, 50])
                      .range([0, 400]);
        //Create the Axis
        var xAxis = d3.svg.axis()
              .scale(axisScale);
        //Create a group Element for the Axis elements and call the xAxis function
        var xAxisGroup = svgContainer.append("g")
                                    .call(xAxis);
    </script>
</body>

任何形式的帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

在D3轴中指定值的最安全方法是使用axis.tickValues。在你的情况下:

.tickValues(d3.range(axisScale.domain()[0], axisScale.domain()[1] + 10, 10));

以下是您更改的代码:

var svgContainer = d3.select("body").append("svg")
  .attr("width", 700)
  .attr("height", 100);

var axisScale = d3.scale.linear()
  .domain([0, 50])
  .range([0, 400]);
var xAxis = d3.svg.axis()
  .scale(axisScale)
  .tickValues(d3.range(axisScale.domain()[0], axisScale.domain()[1] + 10, 10));

var xAxisGroup = svgContainer.append("g")
  .attr("transform", "translate(20,50)")
  .call(xAxis);
path,
line {
  fill: none;
  stroke: black;
  shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.12/d3.min.js"></script>