在线形图中动态绘制多条线 [英] draw multiple lines in line chart dynamically

查看:101
本文介绍了在线形图中动态绘制多条线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据此示例创建多折线图表,并需要基于用户选择动态绘制多条线。代码使用以下方法创建行:

I am trying to create a multi-line chart upon this example, and need to draw multiple lines dynamically based on user selections. The code uses following approach to create the lines:

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

然后创建 valueline()以创建路径:

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

我使用JSON渲染图表,并有一个简单的对象与键 - 值对数组:

I am using JSON to render the charts and have a simple array of Objects with key-value pairs:

data = [{
      "date": "1-Apr-11",
      "primary": 58.13,
      "secondary": 28.13
    }, {
      "date": "1-May-11",
      "primary": 53.98,
      "secondary": 35.13
    }];

这是JSFiddle。

当前代码只能绘制 primary 。任何人都可以建议一个动态的方式来绘制多行?我试图创建第二个 valueline2()函数创建第二行,然后另一个 svg.append(path) valueline2()创建路径。所以行数越多,代码越复杂,所以我不认为这是一个更好的方法。请帮助,真的坚持这一点。

The current code is only able to plot the primary line. Can anyone please suggest a dynamic way to draw multiple lines? I tried to create a second valueline2() function to create the second line, and then another svg.append("path") with line valueline2() to create the path. So the more the lines, the more duplicate code will be there, so I don't think that's a preferable approach. Please help, really stuck with this.

推荐答案

是的,你不应该创建重复。注意,你的示例中的 valueline 是接受 data 并生成行路径的函数(此函数也称为行生成器)。您可以创建一个函数,它将为每个数据列返回不同的函数(行生成器):

Yes, you should not creating duplicates. Note that valueline from your example is function which accepts data and generates line path (this function is also called line generator in API). You can create a function which will return a different function (line generator) per each of your data columns:

    // Define the parametric line generator
    var valueline = function(field) { 
      return d3.svg.line()
        .x(function(d) {
        return x(d.date);
      })
        .y(function(d) {
        return y(d[field]);
      });
    };
  ...

      for (let field of ["primary", "secondary"])
      {
        // Add the valueline path.
        svg.append("path")
          .attr("class", "line") 
          // here you constructing specific line generator and pass data to it  
          .attr("d", valueline(field)(data)); 
      }

这里的工作示例: https://jsfiddle.net/sdnyn8uf/18/ (抱歉,第二个细分没有可悬停的点)

Working example here: https://jsfiddle.net/sdnyn8uf/18/ (sorry, no hoverable points there for the second segment)

这篇关于在线形图中动态绘制多条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆