翻转d3js svg行

时间:2017-10-19 03:09:20

标签: javascript d3.js svg

我想翻转这条线,以便较高的值上升而较低的值下降。我尝试使用<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="paths"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script> <script> var canvas = d3.select(".paths").append("svg") .attr("width", 500) .attr("height", 500); var data = [ {x:10, y:200}, {x:30, y:170}, {x:50, y:70}, {x:70, y:140}, {x:90, y:150}, {x:110, y:120}, {x:130, y:150}, {x:150, y:140}, {x:170, y:110} ]; var group = canvas.append('g') .attr("transform", "scale(1,1)"); var line = d3.svg.line() .x(function(d){ return d.x }) .y(function(d){ return d.y }); group.selectAll("path") .data([data]) .enter() .append("path") .attr("d", line) .attr("fill", "none") .attr("stroke", "red") .attr("stroke-width", 2); </script> </body> </html> ,但它没有输出任何内容。请参阅下面的代码

docker run -i -t ubuntu:14.04 /bin/bash

https://jsbin.com/dayoxon/7/edit?html,output

1 个答案:

答案 0 :(得分:1)

你必须使用一个比例,顺便解决你的另一个问题:你的数据值不应该是(或通常不会是)SVG坐标。

这是线性刻度的基本示例:

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

这里,域从0到200,这是数据中的最大值。然后,这些值将映射到:

.range([height, 0])

其中height是SVG的高度。

最后,使用线生成器中的比例:

var line = d3.svg.line()
  .x(function(d){ return d.x })
  .y(function(d){ return scale(d.y) });

以下是具有该比例的代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
  </head>
  <body>
    <div class="paths"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
    <script>
    var canvas = d3.select(".paths").append("svg")
      .attr("width", 500)
      .attr("height", 300);

    var data = [
      {x:10, y:200},
      {x:30, y:170},
      {x:50, y:70},
      {x:70, y:140},
      {x:90, y:150},
      {x:110, y:120},
      {x:130, y:150},
      {x:150, y:140},
      {x:170, y:110}
    ];

    var group = canvas.append('g');
      
    var scale = d3.scale.linear()
      .domain([0, 200])
      .range([300,0]);

    var line = d3.svg.line()
      .x(function(d){ return d.x })
      .y(function(d){ return scale(d.y) });
    
    
    group.selectAll("path")
      .data([data])
      .enter()
      .append("path")
      .attr("d", line)
      .attr("fill", "none")
      .attr("stroke", "red")
      .attr("stroke-width", 2);


  </script>
  </body>
</html>