首页 > 解决方案 > 以日期为 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

标签: javascriptd3.js

解决方案


GetMonth 将始终给出月份。获取日期并根据日期显示。不理想,但有效。这里的例子


推荐阅读