javascript - 以日期为 x 轴的折线图上的工具提示行为
问题描述
我正在尝试创建一个带有工具提示的折线图,其中 x 轴是日期。
我希望线条和工具提示在 x 轴上的下一个刻度的一半(或类似)之后改变。
主要是我希望行为与这个 bl.ock 相同:http: //bl.ocks.org/wdickerson/64535aff478e8a9fd9d9facccfef8929
您可以在我的 bl.ock 上查看我目前的行为:https ://bl.ocks.org/JulienAssouline/574a52ee2034bcdc1e56ed926f36dd52
它主要工作,但数据只在它传递到 9 月后才发生变化,并且永远不会到达 10 月。
我试图让我的代码适应 bl.ock。问题是显示的 bl.ock 使用年份,而我使用的日期格式似乎是我的主要问题。
这是代码的主要部分:
var tipBox = svg.append("rect")
.attr("width", width)
.attr("height", height)
.attr("opacity", 0)
.on("mousemove", drawTooltip)
.on("mouseout", removeTooltip)
function removeTooltip() {
if (tooltip) tooltip.style('display', 'none');
if (tooltipLine) tooltipLine.attr('stroke', 'none');
}
function drawTooltip(){
const line_hover = xScale.invert(d3.mouse(this)[0]);
// console.log(d3.mouse(this)[0])
console.log(xScale.invert(d3.mouse(this)[0]).getMonth())
console.log(Math.floor(xScale.invert(d3.mouse(this)[0])))
const date_hover = xScale.invert(d3.mouse(this)[0]).getMonth()
// yScale.invert(pos.y)
tooltipLine.attr("stroke", "grey")
.attr("x1", xScale(line_hover))
.attr("x2", xScale(line_hover))
.attr("y1", 0)
.attr("y2", height)
.attr("class", "line_hover")
.style('stroke-width', 1)
tooltip.html(date_hover)
.style("position", "absolute")
.style("background-color", "lightgrey")
.style('display', 'block')
.style('left', d3.event.pageX - 100+ "px")
.style('top', d3.event.pageY - 20+"px")
.selectAll()
.data(dataNest).enter()
.append('div')
.style('color', "black")
.html(function(e){ return e.key + ': ' + e.values.find(function(h){ return (h.Date.getMonth() + 0.5) == (date_hover + 0.5) }).randNumCol})
}
您可以再次查看我的 bl.ock 上的所有代码:https ://bl.ocks.org/JulienAssouline/574a52ee2034bcdc1e56ed926f36dd52
解决方案
GetMonth 将始终给出月份。获取日期并根据日期显示。不理想,但有效。这里的例子
推荐阅读
- python - Python,DataFrame中的未列出数组
- webpack-4 - 从 webpack4 中编译的 SASS 生成 sourcemap
- python - python中二维上最快的迭代
- mysql - 如何在多个 UNION SELECT 之后使用 GROUP BY 而不会收到 NONAGGREGATED COLUMN 错误?
- c - 这个枚举在这个驱动程序中是如何工作的?
- vue.js - Nuxt $vuetify.theme.dark 在我更改页面时重置
- javascript - 使用扩展运算符时如何更新数组内的元素
- google-bigquery - 在 Big Query 中检索覆盖的已保存查询
- html - CSS - 独立的翻译和缩放功能?
- scala - 在 Spark 中使用换行符(\n)在字段中读取文件,用反斜杠(\)转义并且不加引号