在NVD3中向堆叠面积图的y轴添加自定义非均匀标签



我想要几个数据集的堆叠面积图。可能不同寻常的是,我想用y轴来说明每个集合代表什么及其起始值。

。y轴不需要是数据范围内的常规刻度。

:

[
{key: 'the first set', values: [x: 0, y: 4]},
{key: 'the second set', values: [x: 0, y: 10]},
]

y轴应该在4处有一个标记:' the first set: 4 ',在10处有一个标记:' the second set: 10 '

nv.addGraph(function() {
  var chart = nv.models.stackedAreaChart()
    .showLegend(false)
    .showControls(false);
  var data = [
    {
      key: 'first',
      values: [
        { x: 0, y: 2 }, 
        { x: 2, y: 4 }, 
        { x: 4, y: 6 }, 
        { x: 6, y: 8 }
      ]
    }, 
    {
      key: 'second',
      values: [
        { x: 0, y: 4 }, 
        { x: 2, y: 6 }, 
        { x: 4, y: 8 }, 
        { x: 6, y: 10 }
      ]
    } 
  ];
  var firstItemsLabels = ['', 'first', 'second', ''];
  var firstItemsValues = [0, 2, 4, 10];
  //the below doesn't seem to make any difference
  //var firstItemsLabels = ['first', 'second'];
  //var firstItemsValues = [2, 4];
  chart.yAxis.tickValues(firstItemsLabels);
  chart.yAxis.tickFormat(function(d, i) {
    console.log('getting tick format for d: "' + d + '" at i ' + i);
    console.log('for i: ' + i + ' = ' + firstItemsValues[i]);
    var result = firstItemsValues[i];
    return result;
  });
  d3.select('#chart svg')
    .datum(data)
    .call(chart);
  nv.utils.windowResize(chart.update);
  return chart;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.css" rel="stylesheet">
<div id="chart">
  <svg></svg>
</div>

我认为这段代码应该能达到这个目的,但是它没有

该代码段的控制台日志输出…

getting tick format for d: "" at i 0
for i: 0 = 0
getting tick format for d: "first" at i 1
for i: 1 = 2
Error: Invalid value for <g> attribute transform="translate(0,NaN)
getting tick format for d: "0" at i undefined
for i: undefined = undefined
getting tick format for d: "18" at i undefined
for i: undefined = undefined

…我很困惑,因为tickformat正在寻找一个值为18的点,而这个值不在数据集中。

我是在尝试实现不可能的事情吗?如果不是,既然我显然做错了,又怎么能做到呢?

如果我正确理解了你的目标,你可以使用:

  chart.yAxis.tickValues([4,10]);
  chart.yAxis.tickFormat(function(d, i) {
    if (d === 4 || d == 10) {
      return "the first set: " + d
    }
  });

查看这个Plunk的工作示例:http://plnkr.co/edit/sdM14ebvv8cYCvOtX8em?p=preview

最新更新