我已经编写了这段代码,通过唱起滑块来显示条形的过渡,现在我想显示与条形和滑块相对应的X和Y轴。下面是我目前缺少x和y轴的代码,任何人都可以帮我解决这个问题。谢谢

<!DOCTYPE html>
<html lang="en">
<head>
<style>
div#slider{
    width: 940px;
    margin-left: 5%;

    margin-top: 4%;
    }
svg {
    margin-left:3%;
    }
</style>
    <script data-require="[email protected]" data-semver="2.1.4" src="jquery-2.1.4.min.js"></script>
    <link data-require="[email protected]" data-semver="1.10.0" rel="stylesheet" href="jquery-ui-1.10.0.custom.min.css" />
    <script data-require="[email protected]" data-semver="1.10.0" src="jquery-ui.js"></script>
    <script src="d3.v3.min.js"></script>
</head>
<body>
<div id="slider"></div>
<script>
    $(function() {

        $("#slider").slider({
            min: 30,
            max: 950,
            // on slide adjust width of all rects
            slide: function(event, ui) {
                svg.selectAll("rect")
                        .attr("width", function (d) {
                            return Math.min(ui.value * d.rate, d.max);
                        });
            }
        });

        // create svg
        var svg = d3.select("body")
                .append("svg")
                .attr("width", 950)
                .attr("height", 400);


        // add 4 rects
        var data = [
            { row:1, rate:0.4, max:550 },
            { row:2, rate:0.5, max:600 },
            { row:3, rate:0.6, max:700 },
            { row:4, rate:0.7, max:750 },
            { row:5, rate:0.8, max:780 },
            { row:6, rate:0.9, max:800 },
            { row:7, rate:1.0, max:950 },
        ];

        svg.selectAll("rect")
                .data(data)
                .enter()
                .append("rect")
                .attr("x", 20)
                .attr("y", function(d) {
                    return d.row * 30;
                })
                .attr("height", 20)
                .attr("width", 20)
                .style("fill","blue")
                .style("margin-top",20);

    });
</script>
</body>
</html>

最佳答案

您将必须使用d3.scale函数添加轴。有关工作示例,请参见this plnkr

  //add x and y axis
  var x = d3.scale.linear()
    .range([0, 950]);

  var y = d3.scale.linear()
    .range([200, 0]);

  var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

  var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

  x.domain([0, 950]);

  y.domain([0, 7]);

  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(20,250)")
    .call(xAxis);

  svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(20,30)")
    .call(yAxis);

09-16 11:42