nvd3を使ってjavascriptでグラフを表示


nvd3を使うと簡単にかける。データは次のJSON形式でつくる。

[{
  key:'Label',
  values:[{x:0,y:0},{x:1,y:1}]
}]

main.html
<html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>My chart</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.js"></script>
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.css">
        <script src="chart.js"></script>
      </head>
      <body>
        <!-- D3 will use this "svg" tag to render the chart! -->
        <svg></svg>
      </body>
</html>



chart.js
/*These lines are all chart setup.  Pick and choose which chart features you want to utilize. */
nv.addGraph(function() {
  // Creates a new Line chart.
  var chart = nv.models.lineChart()
    .useInteractiveGuideline(true)
    .showLegend(true)
    .showYAxis(true)
    .showXAxis(true);
 
  // Tells NVD3 to display values with two decimal places.
  chart.xAxis
    .axisLabel('x')
    .tickFormat(d3.format('.2f'));
 
  chart.yAxis
    .axisLabel('y')
    .tickFormat(d3.format('.2f'));
 
  // Select the "svg" tag and render the chart.
  d3.select('svg')
    .datum(sinAndCos())
    .call(chart);
 
  // This will render the chart every time the
  // window is resized, so it will always fit the
  // screen.
  nv.utils.windowResize(function() {
    chart.update()
  });
 
  return chart;
});
/**************************************
 * Simple test data generator
 */
function sinAndCos() {
  var sin = [],sin2 = [],
      cos = [];

  //Data is represented as an array of {x,y} pairs.
  for (var i = 0; i < 100; i++) {
    sin.push({x: i, y: Math.sin(i/10)});
    sin2.push({x: i, y: Math.sin(i/10) *0.25 + 0.5});
    cos.push({x: i, y: .5 * Math.cos(i/10)});
  }
  //Line chart data should be sent as an array of series objects.
  return [
    {
      values: sin,      //values - represents the array of {x,y} data points
      key: 'Sine Wave', //key  - the name of the series.
      color: '#ff7f0e'  //color - optional: choose your own line color.
    },
    {
      values: cos,
      key: 'Cosine Wave',
      color: '#2ca02c'
    },
    {
      values: sin2,
      key: 'Another sine wave',
      color: '#7777ff',
      area: true      //area - set to true if you want this line to turn into a filled area chart.
    }
  ];
}

bibliography
Simple Line Chart - NVD3 
NVD3を使って、AngularJSで作ったハイブリッドアプリのグラフを統合しよう : アシアルブログ 

コメント

人気の投稿