NVD3.js yAxis 和工具提示的精度不同

NVD3.js yAxis and tooltip different percision

本文关键字:精度 工具提示 js yAxis NVD3      更新时间:2023-09-26

我正在使用NVD3.js来显示多折线图。

我希望 yAxis 显示为 2 个十进制数字

编辑的答案

 var chart;
    nv.addGraph(function () {
        chart = nv.models.lineChart()
        .options({
            margin: { left: 140, bottom: 50 },
            x: function (d, i) {
                return i;
            },
            showXAxis: true,
            showYAxis: true,
            transitionDuration: 250,
            tooltips: true,
            tooltipContent: function (key, x, y, e, graph) {
                return '<h3>' + key + '</h3>' +
                       '<p>' + e.point.y + ' at ' + x + '</p>'
            }
        });
        // chart sub-models (ie. xAxis, yAxis, etc) when accessed directly, return themselves, not the parent chart, so need to chain separately
        chart.xAxis
            .axisLabel("Maturity")
            .tickFormat(function(d) { return pivotedData[0].values[d].x; });
        chart.yAxis
            .axisLabel('Model Spread').tickFormat(d3.format(',.2f'));

        d3.select('#chart1 svg')
          .datum(pivotedData)
          .call(chart);
        //TODO: Figure out a good way to do this automatically
        nv.utils.windowResize(chart.update);
        chart.dispatch.on('stateChange', function (e) { nv.log('New State:', JSON.stringify(e)); });
        return chart;
    });

但是在工具提示的行中,我想显示到小数点后 12 位。

这可能吗?

可以设置调用的函数,以通过图表对象的.tooltipContent设置工具提示内容的格式。默认函数定义如下。

tooltip = function(key, x, y, e, graph) {
    return '<h3>' + key + '</h3>' +
           '<p>' +  y + ' at ' + x + '</p>'
}

您可以根据自己的喜好在其中格式化y的值。请注意,y定义为

yAxis.tickFormat()(lines.y()(e.point, e.pointIndex))

这意味着轴的刻度格式会影响它,因此为了在那里实现更高的精度,您需要直接获取值 - lines可以通过chart.lines访问。

在 nvd3 源中,它们有这样的行(折线图):

 interactiveLayer.dispatch.on('elementMousemove', function(e) {
  ...
      var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex));
      interactiveLayer.tooltip
              .position({left: pointXLocation + margin.left, top: e.mouseY + margin.top})
              ...
              .valueFormatter(function(d,i) {
                 return yAxis.tickFormat()(d);
              })
              .data(
                  {
                    value: xValue,
                    series: allData
                  }
              )();
...
}

因此,如果你想覆盖像tooltip.contentGenerator这样的东西,你就会被它给你的数据所困。 我认为做到这一点的一个好方法是为工具提示 x 格式化程序或其他东西提供一个设置器,然后它将在轴格式化程序上使用它。 或者只是发送原始数据以及值和系列。

我的用例是我在图表上显示 7 天的时间刻度,我只勾选每天的开始。 但是,在工具提示上,我想提供该数据的更详细视图。

这是我特定于指南工具提示的拉取请求

https://github.com/novus/nvd3/pull/444

调用:chart.tooltipXAxisFormatter(d3.time.format(toolTipFormat));将设置它。