将缩放数据传递到D3.js中的x和y轴?

时间:2014-11-11 16:02:05

标签: javascript svg d3.js scaling

我已使用以下代码可视化我在csv文件中的数据。我缩放了数据以动态地适应svg元素,但即使我将scale函数传递给两者,x轴和y轴仍显示预缩放值。有人知道如何解决这个问题吗?

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>D3 Test</title>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <style>
    .axis path,
        .axis line {
            fill: none;
            stroke: black;
            shape-rendering: crispEdges;
    }
        .axis text {
            font-family: sans-serif;
            font-size: 11px;
    }
    </style>
</head>
<body>
    <script type="text/javascript">

        //Width and height
        var w = 500;
        var h = 300;
        var padding = 80;
        var dataset = []
        var generateVisualization = function(){
            //Create scale functions
            var xScale = d3.scale.linear()
                             .domain([d3.min(dataset, function(d) { return d[0]; }), d3.max(dataset, function(d) { return d[0]; })])
                             .range([padding, w - padding]);

            var yScale = d3.scale.linear()
                             .domain([d3.min(dataset, function(d) { return d[1]; }), d3.max(dataset, function(d) { return d[1]; })])
                             .range([h - padding, padding]);

            //Define X axis
            var xAxis = d3.svg.axis()
                          .scale(xScale)
                          .orient("bottom")
                          .ticks(5);

            //Define Y axis
            var yAxis = d3.svg.axis()
                          .scale(yScale)
                          .orient("left")
                          .ticks(5);

            //Create SVG element
            var svg = d3.select("body")
                    .append("svg")
                    .attr("width", w)
                    .attr("height", h);

            //Create circles
            svg.append("g")
           .attr("id", "circles")
           .selectAll("circle")
           .data(dataset)
           .enter()
           .append("circle")
           .attr("cx", function(d) {
                return xScale(d[0]);
           })
           .attr("cy", function(d) {
                return yScale(d[1]);
           })
           .attr("r", 2);

            //Create X axis
            svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + (h - padding + 5) + ")")
            .call(xAxis);

            //Create Y axis
            svg.append("g")
            .attr("class", "y axis")
            .attr("transform", "translate(" + (padding - 5) + ",0)")
            .call(yAxis);
        };

        d3.csv("OuputMatrix2.csv", function(error, d) {
            dataset = d.map(function(d) { return [ +d["x"], +d["y"] ]; 
            });
            generateVisualization();});
    </script>
</body>
</html>

以下是输出的屏幕截图: https://www.dropbox.com/s/2th83r4r42nn4el/Screenshot%202014-11-11%2015.45.55.png?dl=0

0 个答案:

没有答案