【问题标题】:Adding custom non-uniform labels to a Y-axis of a stacked area chart in NVD3在 NVD3 中向堆积面积图的 Y 轴添加自定义非均匀标签
【发布时间】:2015-09-10 22:38:36
【问题描述】:

我想要几个数据集的堆积面积图。可能不寻常的是,我想使用 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>

我认为这个 sn-p 中的代码应该可以实现,但它没有

该 sn-p 的控制台日志输出...

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。

我是否正在尝试实现一些不可能的事情?如果不是,我明明做错了,怎么办?

【问题讨论】:

    标签: nvd3.js


    【解决方案1】:

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

      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

    【讨论】:

    • 啊,这不是我所追求的,但我认为它可以帮助我迈出下一步。 i 变量显然没有做我认为的那样。
    猜你喜欢
    • 1970-01-01
    • 2013-09-22
    • 2015-11-17
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多