gpt4 book ai didi

javascript - d3 将刻度日期变换到 x 位置?

转载 作者:行者123 更新时间:2023-12-03 09:26:54 24 4
gpt4 key购买 nike

我有一个线性 y 尺度和一个时间序列 x 尺度。我想在 x/y 值后面放置一个叠加层(类似于 http://bl.ocks.org/mbostock/3902569 )。

问题是我无法转换为正确的 x 比例值;例如,当我将鼠标悬停在图表上时,它会输出(此数据是正确的):

{ y: 0.05, x: "2015-07-26 15:08:47" }
{ y: 0.05, x: "2015-07-26 15:08:47" }
{ y: 0.05, x: "2015-07-26 15:08:47" }

现在我想使用这些数据在该位置绘制一个点;问题是我无法复制上面的 bl.locks.org 示例,并且 transform 无法使用 x 位置作为日期;那么如何将 x 日期转换为图表上的点呢?

我的mousemove如下:

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 varea = d3.svg.area()
.defined(function(d) { return d.y != null; })
.x(function(d) { return x(parseDate(d.x)); })
.y0(height)
.y1(function(d) { return y(d.y); });

var svg = d3.select(".swatch").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 + ")");

x.domain(d3.extent(data, function(d) { return parseDate(d.x); }));
y.domain([0, d3.max(data, function(d) {
if (d.y >= 1) {
return d.y
}

return 1;
})]);

svg.append("path")
.attr("class", "area")
.attr("d", varea(data));

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

svg.append("g")
.attr("class", "y axis")
.call(yAxis);

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

focus.append("circle")
.attr("r", 4.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", function() {
var x0 = x.invert(d3.mouse(this)[0]);

var bisect = d3.bisector(function(d) { return parseDate(d.x); }).right;

var item = data[bisect(data, x0)];

focus.attr("transform", "translate(" + x(parseDate(item.x)) + "," + y(item.y) + ")");
focus.select("text").text(item.y);

console.log(x(parseDate(item.x)));
console.log(y(item.y));
});

此代码在控制台中产生如下错误:

Unexpected value translate(NaN,120) parsing transform attribute.

那么,问题是如何将日期转换为正确的坐标?

最佳答案

好吧,我的代码存在一些问题。

我没有将 x 值解析为日期;所以我开始使用 parseDate 解析它(参见示例代码),然后将其传递给 x 比例;这使我能够在图表上找到正确的位置。

第二个问题是 display 设置不正确(在 Firefox 中将其设置为 null 不允许它显示)。因此,我将其更改为 display: inline;,它开始显示在图表上。

关于javascript - d3 将刻度日期变换到 x 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31642117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com