如何在折线图中显示最新值

时间:2016-05-03 16:25:12

标签: javascript d3.js charts

我无法访问CSV的最后一个值(行),以便在我的折线图中悬停显示。我需要将值显示为文本,但也要用作Y坐标以与行的末尾对齐。 这就是我所拥有的。第一部分有效,但不是第二部分(介于///之间):

function mouseover(d) {
d3.select(d.corporation.line).classed("corporation--hover", true);
d.corporation.line.parentNode.appendChild(d.corporation.line);
focus.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")");
focus.select(".corpname").text(d.corporation.name);
focus.select(".ranking").text(d.value);
/////
focus.append("text")
.datum(function(d) { return {name: d.corporation.name, value: d.corporation.value[d.corporation.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.values) + ")"; })
.text(function(d) { return d.value; });
/////
}

我尝试了几种不同的变化而没有成功。如果有人能达到巅峰,我会很高兴。

PLUNK在这里:http://plnkr.co/edit/1Nf992jYjSGyKhLhaij5?p=preview

谢谢!

1 个答案:

答案 0 :(得分:0)

以下是访问与线元素绑定的数据的方式:this.__data__

首先,让我们创建一个变量来访问您的数据,特别是值数组:

var that = this.__data__.corporation.values;

然后,我们可以得到行尾的日期和值:

var thatLength = that.length;
var thatValue = that[thatLength - 1].value;
var thatDate = that[thatLength - 1].date;

显示文字:

someLegend
.attr("x", (x(yearFormat(thatDate))*-1)-90)
.attr("y", y(thatValue))
.text(thatValue);

以下是plunker:http://plnkr.co/edit/4HquzuJ6FJeZvEVWuUS5?p=preview

PS:我创建了这个变量someLegend因为我没有时间理解translate的{​​{1}}逻辑。