我需要在实时折线图中的SVG路径末尾绘制圆圈。我使用d3.js绘制图表。一切都很好,但这个麻烦使我感到困惑。
请告诉我我的代码有什么问题并帮助我找到更好的解决方案。
谢谢!
JS代码:
var GraphIndex = (function() {
var n = 10,
duration = 15000,
now = new Date(Date.now() - duration),
random = d3.random.normal(0, 100),
data = d3.range(n).map(random);
var width = 379,
height = 138;
// X axis
var x = d3.time.scale()
.domain([now - (n - 2) * duration, now - duration])
.range([0, width - 40]);
// Y axis
var y = d3.scale.linear()
.domain([(-1)*d3.max(data) - 100, d3.max(data) + 100])
.range([height, 0]);
var line = d3.svg.line()
.interpolate("linear")
.x(function(d, i) { return x(now - (n - 1 - i) * duration); })
.y(function(d, i) { return y(d); });
var svg = d3.select(".graph-holder").append("svg")
.attr("width", width)
.attr("height", height + 30);
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width - 40)
.attr("height", height);
// X Axis
var axis = svg.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(0," + height + ")")
.call(x.axis = d3.svg.axis().scale(x).orient("bottom").ticks(d3.time.minutes, 1));
// Line
var path = svg.append("g")
.attr("clip-path", "url(#clip)")
.attr("class", "path-area")
.append("path")
.data([data])
.attr("class", "line")
.attr("id", "myPath");
//Draw the Circle
var circle = d3.select(".path-area")
.append("svg:circle")
.attr("cx", 335)
.attr("cy", y(data[n - 2]))
.attr("r", 4)
.attr("class", "circle");
this.tick = (function(){
now = new Date();
x.domain([now - (n - 2) * duration, now - duration]);
y.domain([(-1)*d3.max(data) - 100, d3.max(data) + 100]);
var d = random()
data.push(d);
// redraw the line
svg.select(".line")
.attr("d", line)
.attr("transform", null);
// slide the x-axis left
axis.transition()
.duration(duration)
.ease("linear")
.call(x.axis);
// slide the line left
path.transition()
.duration(duration)
.ease("linear")
.attr("transform", "translate(" + x(now - (n - 1) * duration) + ")")
.each("end", tick);
circle.transition()
.duration(duration)
.ease("linear")
.attr("transform", "translate(0, " + y(d) + ")");
// pop the old data point off the front
data.shift();
});
this.tick();
});
GraphIndex();
HTML code:
<div class="graph-holder"></div>
CSS代码:
.graph-holder {
position: relative;
width: 379px; height: 138px;
}
.x-axis line {
shape-rendering: auto;
stroke-width: 2px;
}
.x-axis path,
.x-axis line {
fill: none;
stroke: none;
shape-rendering: crispEdges;
}
.x-axis .tick {
color: #fff;
stroke: #fff;
font-size: .75em;
}
.line {
fill: none;
stroke: #fff;
stroke-width: 2.5px;
}
circle {
fill: #fff;
}
答案 0 :(得分:1)
您是否尝试过调整圈子的cy
而不是翻译它?您的Y轴没有链接,因此无需转换坐标系。
所以而不是
.attr("transform", "translate(0, " + y(d) + ")");
试
.attr("cy", function() { return y(data[data.length-2]); });