Add points (x,y) to a d3 multi-line graph with time scale x-axis

时间:2015-09-01 22:27:00

标签: javascript d3.js linechart

I'm currently attempting to build a a multi-line graph with a d3.time.scale() for the x-axis.

I'm trying to add circles to each point on lines of the graph, but have been unsuccessful thus far.

When I do something like:

.attr('cx', function(d){ return x(d.price) })

I get a negative number.

I was thinking of setting up another scale (pointsScale) to handle this but have been largely unsuccessful.

What am I doing wrong?

Please refer to my JSBin for the code.

1 个答案:

答案 0 :(得分:1)

您在这里遇到了一些问题:

  • 由于你把x轴作为时间尺度,我猜你真的希望价格成为y变量,而date是x变量。这就是x(d.price)为负的原因 - d3试图将价格解释为日期,而这并不是最有意义的。因此,请使用以下代码替换上面的代码:.attr('cy', function(d){ return y(d.price) })
  • 为了实际显示圆圈,他们需要设置三个参数:cxcyr。由于d3已经知道您的x轴是时间刻度,因此您可以使用cx设置.attr('cx', function(d){ return x(d.date) })。您可以将r设置为圆圈所需的半径。只需选择一个,否则它将默认为0,您将无法看到圆圈。例如,.attr('r', 4)会将半径设置为完全可见的值4。
  • 您在绘制线条之前绘制圆圈。结果,线条被绘制在圆圈上,看起来有点怪异。因此,如果您想避免使用,请将圈代码移到行代码之后。

总而言之,这大致就是创建圈子的代码应该是什么样子,它应该在您声明var paths之后继续:

    var circles = company.selectAll('circle')
      .data(function(d){ return d.values; })
      .enter().append('circle')
      .attr('cy', function(d){
        return y(d.price);}) //Price is the y variable, not the x
      .attr('cx', function(d){
        return x(d.date);}) //You also need an x variable
      .attr('r',4); //And a radius - otherwise your circles have
                    //radius 0 and you can't see them!

更新了jsbin: http://jsbin.com/gorukojoxu/edit?html,console,output