D3.js下拉列表:删除折线图数据

时间:2018-02-13 16:51:09

标签: javascript d3.js

我是D3.js和Javascript的新手,我正在使用下拉列表调用不同的数据集

我在查看如何在显示新之前删除旧数据时遇到问题。

现在,当您从下拉列表中选择选项2时,它会覆盖选项1.我已经在.exit.remove函数上阅读了一些内容,但似乎无法找出我的代码中我需要放置它的位置。

我主要基于Mike Bostock的线图:https://bl.ocks.org/mbostock/3902569



date	close
1-Jun-15	77.34
1-Jul-15	74.66
1-Aug-15	72.26
1-Sep-15	70.28
1-Oct-15	70.76
1-Nov-15	65.63
1-Dec-15	65.39
1-Jan-16	68.33
1-Feb-16	69.35
1-Mar-16	73.53
1-Apr-16	67.63
1-May-16	75.86
1-Jun-16	70.19
1-Jul-16	74.14
1-Aug-16	73.28
1-Sep-16	72.6
1-Oct-16	75.21
1-Nov-16	78.13
1-Dec-16	78.11
1-Jan-17	77.7

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

body {
font: 15px sans-serif;
}

h1{
text-align: center;
color:#4CAF50;
font: 30px sans-serif;
text-transform: uppercase;
}

h2{
text-align:center;
}

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

.x.axis path {
  display: none;
}

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

.overlay {
fill: none;
pointer-events: all;
}

.focus circle {
fill: none;
stroke: black;
}

</style>

<h1 id="Title">Commodity</h1>
<h2>
<select onchange="loadData()" id="metric">
<option value ="Glass">Glass ($/lbs)</option>
<option  value ="Aluminum">Aluminum ($/ton)</option>
</select>
</h2>

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


<script>
var margin = {top: 20, right: 50, bottom: 30, left: 50},
    width = 1200 - margin.left - margin.right,
    height = 700 - margin.top - margin.bottom;

var parseDate = d3.time.format("%d-%b-%y").parse,
    bisectDate = d3.bisector(function(d) { return d.date; }).left,
    formatValue = d3.format(",.2f"),
    formatCurrency = function(d) { return "$" + formatValue(d); };

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.selectAll("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 + ")");

var loadData = function() {
var metric = document.getElementById('metric').selectedOptions[0].value;
var dataFile = metric + '.csv'
d3.csv(dataFile, function(data) {
    data.forEach(function(d) {
    d.date = parseDate(d.date);
    d.close = +d.close;
});

  data.sort(function(a, b) {
    return a.date - b.date;
  });

// this tells DOM where to place the data 
  x.domain([data[0].date, data[data.length - 1].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");

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

  var focus = svg.append("g")
      .attr("class", "focus")
      .style("display", "none");

  focus.append("circle")
      .attr("r", 8.5);

  focus.append("text")
      .attr("x", 9)
      .attr("dy", ".35em");

  svg.append("rect")
      .attr("class", "overlay")
      .attr("width", width)
      .attr("height", height)
      .on("mouseover", function() { focus.style("display", null); })
      .on("mouseout", function() { focus.style("display", "none"); })
      .on("mousemove", mousemove);

  function mousemove() {
    var x0 = x.invert(d3.mouse(this)[0]),
        i = bisectDate(data, x0, 1),
        d0 = data[i - 1],
        d1 = data[i],
        d = x0 - d0.date > d1.date - x0 ? d1 : d0;
    focus.attr("transform", "translate(" + x(d.date) + "," + y(d.close) + ")");
    focus.selectAll("text").text(formatCurrency(d.close));
  }
})
}
loadData()
</script>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

加载第二个集合在旧路径上添加新路径的原因是由于此代码:

->

您需要选择现有的路径元素,并更新其&#34; d&#34;而不是始终追加新路径。具有来自svg.append("path") .datum(data) .attr("class", "line") .attr("d", line); 函数的新路径的属性。有关此技术的更多信息,请参见General Update Pattern页面。

虽然我没有对其进行测试,但您的代码应该更新为:

line()

var path = svg.selectAll("path").datum(data); path.enter() .append("path") .attr("class", "line"); path.attr("d", line); 仅返回那些尚未在DOM中创建的路径元素的选择。所以第一次,它附加一个路径元素并设置它的类。之后,不会创建新的路径元素。但在这两种情况下,&#34; d&#34; attr设置为根据数据构建的行。

答案 1 :(得分:0)

<select onchange="updateData()" id="metric">事件:

上使用此功能
function updateData() {
  var metric = document.getElementById('metric').selectedOptions[0].text;
  var dataFile = 'data_' + metric + '.csv'
  d3.csv(dataFile, function(data) {
        data.forEach(function(d) {
        d.date = parseDate(d.date);
        d.close = +d.close;
      });

      // Scale the range of the data again 
      x.domain(d3.extent(data, function(d) { return d.date; }));
      y.domain([0, d3.max(data, function(d) { return d.close; })]);

    // Select the section we want to apply our changes to
    var svg = d3.select("body").transition();

    // Make the changes
        svg.select(".line")   // change the line
            .duration(750)
            .attr("d", line(data));

        svg.select(".x.axis") // change the x axis
            .duration(750)
            .call(xAxis);
        svg.select(".y.axis") // change the y axis
            .duration(750)
            .call(yAxis);

    });
}