nvd3相同时间戳的正负值

时间:2018-09-10 13:24:17

标签: javascript d3.js nvd3.js

使用nvd3库,我试图在条形图(如两个倒置的条形图)中显示相同的“ x”值的正和负“ y”值。这些值会显示出来,但负值也会在y轴的正比例上绘制。

如果我只显示负值,则它可以正常工作,但在两种情况下,它都无法按预期工作。

下面是我当前在代码中所显示的内容:

var chart;
nv.addGraph(function() {
  chart = nv.models.historicalBarChart();
  chart.useInteractiveGuideline(true);
  chart.xAxis.axisLabel("Time (s)");
  chart.yAxis.axisLabel('Voltage (v)');

  d3.select('#chart svg')
    .datum(sinAndCos())
    .call(chart);

  nv.utils.windowResize(chart.update);
  return chart;
});

function sinAndCos() {
  var sin = [], cos = [];
    
  for (var i = 0; i < 100; i++) {
    sin.push({
      x: i,
      y: i
    });

    cos.push({
      x: i,
      y: -(i)
    });
  }

  return [
  {
      values: sin,
      key: "Sine Wave",
      color: "#ff7f0e"
    },
    {
      values: cos,
      key: "Cosine Wave",
      color: "#2ca02c"
    }
  ];
}
 text {
   font: 12px sans-serif;
 }

 svg {
   display: block;
 }

 html, body, #chart, svg {
   margin: 0px;
   padding: 0px;
   height: 100%;
   width: 100%;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.6/nv.d3.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.6/nv.d3.min.css" rel="stylesheet"/>

<div id="chart">
  <svg></svg>
</div>

以下是JSFiddle的链接,其中再现了该问题:https://jsfiddle.net/prerak6962/a1zh9o4e/14/

我有什么需要补充的吗?

1 个答案:

答案 0 :(得分:1)

使用其他条形图可获得更好的结果

  • chart = nv.models.discreteBarChart();
  • chart = nv.models.multiBarChart();

var chart;
nv.addGraph(function() {
  //chart = nv.models.historicalBarChart();
  chart = nv.models.multiBarChart();
  //chart.useInteractiveGuideline(true);
  chart.xAxis.axisLabel("Time (s)");
  chart.yAxis.axisLabel('Voltage (v)');

  d3.select('#chart svg')
    .datum(sinAndCos())
    .call(chart);

  nv.utils.windowResize(chart.update);
  return chart;
});

function sinAndCos() {
  var sin = [], cos = [];
    
  for (var i = 0; i < 100; i++) {
    sin.push({
      x: i,
      y: i
    });

    cos.push({
      x: i,
      y: -(i)
    });
  }

  return [
  {
      values: sin,
      key: "Sine Wave",
      color: "#ff7f0e"
    },
    {
      values: cos,
      key: "Cosine Wave",
      color: "#2ca02c"
    }
  ];
}
 text {
   font: 12px sans-serif;
 }

 svg {
   display: block;
 }

 html, body, #chart, svg {
   margin: 0px;
   padding: 0px;
   height: 100%;
   width: 100%;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.6/nv.d3.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.6/nv.d3.min.css" rel="stylesheet"/>

<div id="chart">
  <svg></svg>
</div>