Javascript d3.js折线图工具提示内容未显示
我试图在我的d3.js行图表行工具提示上显示csv文件的温度和时间戳列下的数据。我希望在工具提示上显示相应的日期和温度 这是我从控制台得到的错误 “未捕获的TypeError:无法读取未定义的属性'timestamp' 在SVGPathElement(index.js:70) 在SVGPathElement.(d3.v5.js:2) div.html(formatTime((d.timestamp))+“Javascript d3.js折线图工具提示内容未显示,javascript,variables,d3.js,Javascript,Variables,D3.js,我试图在我的d3.js行图表行工具提示上显示csv文件的温度和时间戳列下的数据。我希望在工具提示上显示相应的日期和温度 这是我从控制台得到的错误 “未捕获的TypeError:无法读取未定义的属性'timestamp' 在SVGPathElement(index.js:70) 在SVGPathElement.(d3.v5.js:2) div.html(formatTime((d.timestamp))+“”+(+d.temperature)) 我希望日期和温度应该显示在工具提示上 让svg=d
”+(+d.temperature)) 我希望日期和温度应该显示在工具提示上
让svg=d3.select('svg'),
高度=+svg.attr('height'),
宽度=+svg.attr('width');
设formatTime=d3.timeFormat(“%m/%d/%Y”);
常量呈现=数据=>{
const title=‘一段时间内的约定(总计:946K)’;
const xValue=d=>d.timestamp;
常数y值=d=>d.温度;
常量边距={顶部:60,右侧:60,底部:88,左侧:105};
const innerwidth=width-margin.left-margin.right;
const innerheight=高度-margin.top-margin.bottom;
常量xScale=d3.scaleTime()
.域(d3.范围(数据,xValue))
.范围([0,innerwidth-150])
.nice();
常量yScale=d3.scaleLinear()
.domain([0,d3.max(数据,d=>d.temperature)])
.范围([innerheight,0])
.nice();
常量g=svg.append('g')
.attr('transform','translate(${margin.left},${margin.top+30})`);
让parseDate=d3.timeFormat(“%m/%d/%Y”);
常量xAxis=d3.axisBottom(xScale)
.tickFormat(解析日期)
.1(5)
//定义工具提示的div
让div=d3。选择(“body”)。追加(“div”)
.attr(“类”、“工具提示”)
.style(“不透明度”,0)
.style(“显示”、“空”);;
让yAxisTicFormat=number=>d3.format('.1s')(number)
常数yAxis=d3.轴左(yScale)
.1(35)
.tickFormat(yAxisTicFormat)
;
常量yAxisG=g.append('g').call(yAxis);
yAxisG.selectAll('.domain').remove();
const xAxisG=g.append('g').call(xAxis)
.attr('transform','translate(0,${innerheight})`);
选择('.domain').remove();
常量lineGenerator=d3.line()
.x(d=>xScale(xValue(d)))
.y(d=>yScale(y值(d)))
.曲线(d3.曲线基);
g、 追加('路径')
.attr('类','行路径')
.attr('d',线路生成器(数据))
.on(“鼠标悬停”,功能(d){
过渡部()
.持续时间(500)
.style(“不透明度”,1)
.样式(“显示”、“块”);
console.log(xValue);
div.html(formatTime((d.timestamp))+“
”+(+d.temperature))
.style(“左”(d3.event.pageX-1)+“px”)
.style(“top”,(d3.event.pageY-28)+“px”);
})
.开启(“鼠标出”,功能(d){
过渡部()
.持续时间(500)
.style(“不透明度”,0);});;
g、 追加('文本')
.attr('class','title')
.attr('y',-40)
.文本(标题);
};
d3.csv('temperature-in-san-francisco.csv')。然后(数据=>{
//console.log(数据)
data.forEach(d=>{
d、 时间戳=新日期(d.时间戳);
d、 温度=+d.温度*1000;
});
渲染(数据);
//console.log(数据)
})
看起来您认为mouseover事件上会返回不同的数据点,具体取决于光标接触行的位置,但需要注意的是,该行只是由路径定义字符串定义的单个svg元素
数据数组被传递到行生成器,该行生成器返回一个定义行的字符串,该字符串被设置为路径的d
(对于定义而不是数据(可能))属性。已创建svgpath
元素,但未将任何数据绑定到该元素
那么,
div.html(formatTime((d.timestamp))
抛出的引用错误是没有数据绑定到路径
元素,因此回调的第一个参数(d)返回未定义
如果希望用户能够触摸线上的不同位置并查看数据,则可以使用用于线定义的相同比例在该线上创建点(圆)。单个圆
元素将绑定数据
有许多方法可以在鼠标悬停在圆上时显示工具提示。最简单的似乎是Lars Kotthoff建议的,它不需要鼠标悬停侦听器,而是使用浏览器的内置功能,在悬停时显示元素的标题(这来自Lar的示例):
d3.selectAll("circle")
.data(data)
.enter()
.append("svg:circle")
.attr('cx', d => xScale(d.timestamp))
.attr('cy', d => yScale(d.temperature))
.attr('r', 3)
.attr('fill', 'steelblue')
.append("svg:title")
.text(function(d) { return d.x; });