如何在D3中为折线图创建平均线

时间:2016-02-10 10:04:38

标签: d3.js

我可以使用TSV折线图创建折线图。现在我想创建一个平行于x轴的平均线。请帮忙怎么做

<!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  display: none;
}

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 1.5px;
}

</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>

var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var formatDate = d3.time.format("%d-%m-%y");

var x = d3.time.scale()
    .range([0, width]);

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

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

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

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

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.tsv("line.tsv", type, function(error, data) {
  if (error) throw error;

  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain(d3.extent(data, function(d) { return d.close; }));

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Time Difference (sec)");

  svg.append("path")
      .datum(data)
      .attr("class", "line")
      .attr("d", line);


});

function type(d) {
  d.date = formatDate.parse(d.date);
  d.close = +d.close;
  return d;
}

</script>

约会 0 1 19-09-15 11 20-09-15 12 21-09-15 2 22-09-15 20 23-09-15 13 24-09-15 4 25-09-15 4 26-09-15 5 27-09-15 1 28-08-16 32 29-08-16 23 01-08-16 12 02-08-16 5 03-08-16 4 04-08-16 10 05-08-16 20 06-08-16 22 07-08-16 1 08-08-16 3

1 个答案:

答案 0 :(得分:1)

关于为什么你做的不起作用,你试图在你的页面上得到一个可以识别的元素:

("document.getElementByID(‘TextBoxProductName’).value = arguments[0]", "John")

你可能没有一个具有可识别特征的元素?

当你想要找到一个具有id的元素时,你知道它将是唯一的,所以你可以快速/简单地直接将它作为目标:

element(by.id('TextBoxProductName'))

// or in shorthand
$(#TextBoxProductName)

将输入文本发送到其中,使用sendKeys:

$(#TextBoxProductName).sendKeys('John')

如果您遇到的问题不是发送密钥,请告知我们,而是定位元素,我们可以解决与弹出框有关的问题

相关问题