简体   繁体   English

一页上有多个多系列d3折线图

[英]Multiple multi-series d3 line charts on one page

Using d3 I want to draw several time series line charts on a single page, each one featuring two lines. 我想使用d3在单个页面上绘制多个时间序列折线图,每个页面都有两条折线。

Using the example on this page for multiple charts, I've got code working with single lines on each chart. 使用此页面上的示例显示多个图表,我在每个图表上使用了单行代码。 But I'm not sure how best to modify that example to work with multi-line charts. 但是我不确定如何最好地修改该示例以使用多折线图。

The example does this: 该示例执行此操作:

d3.csv("sp500.csv", function(data) {
  var formatDate = d3.time.format("%b %Y");

  d3.select("#example")
      .datum(data)
    .call(timeSeriesChart()
      .x(function(d) { return formatDate.parse(d.date); })
      .y(function(d) { return +d.price; }));
});

with TimeSeriesChart() defined in this file . 在此文件中定义了TimeSeriesChart()

How would I best adapt this to cope with two (or more) lines (with the same x-axis values, and the same y scales)? 我怎样才能最好地适应两条(或更多)线(具有相同的x轴值和相同的y比例尺)?

FWIW, my data is in JS arrays/hashes, rather than being read from CSV, but I guess the principle will be the same. FWIW,我的数据在JS数组/哈希中,而不是从CSV中读取,但是我想原理是一样的。

You can pass in your data structure that contains data for several lines in the same way. 您可以以相同的方式传入包含多行数据的数据结构。 The only difference would in how you would handle the data in the referenced file. 唯一的区别在于您如何处理引用文件中的数据。 You need to change the function in 您需要更改功能

selection.each(function(data) {

First, you need to adapt the preprocessing being done and similarly the code that determines the limits of the axes. 首先,您需要调整正在进行的预处理,并且类似地确定轴极限的代码。 Further down, you would change 再往下走,你会改变

// Update the line path.
  g.select(".line")
      .attr("d", line); 

to something like

g.selectAll(".line").data(<data for your two lines here>)
 .enter()
 .append("path")
 .attr("class", "line")
 .attr("d", line);

and remove the line 并删除线

gEnter.append("path").attr("class", "line");

before that. 在那之前。

The exact changes will depend on the format that you're passing in. 确切的更改将取决于您传递的格式。

An alternative (and if you're just starting probably easier) approach would be to simply add the additional data in a new attribute, add a new line generator that accesses that data and repeat the code that generates the line and calls the line generator with a different class name and the different generator. 另一种替代方法(如果您可能刚刚开始,可能会更简单)是将其他数据简单地添加到新属性中,添加新的行生成器以访问该数据,并重复生成行的代码并使用以下命令调用行生成器不同的类名和不同的生成器。 This is a hacky approach that I wouldn't recommend in general, but it might be easier to get started that way. 通常,我不建议您使用这种骇人听闻的方法,但以这种方式开始可能会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM