【问题标题】:Showing JSON format in C3 (D3)在 C3 (D3) 中显示 JSON 格式
【发布时间】:2016-02-13 15:13:15
【问题描述】:

如何基于此 JSON 格式在 C3(或 D3)图中显示数据:

[{"Type":"Dog","Number":13},{"Type":"Cat","Number":21}]

这是带有来自 JSON 数据的角度控制器,问题在于定义 keys 属性。我对将类型与数字合并有点困惑。请看一下plunker

angular.module('c3example', [])
  .controller('ExampleCtrl', function($scope){
     d3.json('/chartData.json', function(err, data){
        if(err){ throw err; }
        $scope.data = data;

        $scope.chart_types = c3.generate({
            bindto: d3.select('#chart'),
            size: {
                weight: 640,
                height: 480
            },
            data: {
                json: $scope.data,
                keys: {
                    value: ['Dog', 'Cat'],
                },
                type: 'bar'
             },
        bar: {
            width: {
                ratio: 0.5 // 
            }
        }
        });
    });
  })

在 HTML 中绑定:

<!DOCTYPE html>
    <html>
      <body ng-app="c3example" ng-controller="ExampleCtrl">
        <div class="row">
          <div id="chart" build-chart></div>
        </div>
      </body>
    </html>

【问题讨论】:

  • 不幸的是 plunker 甚至没有加载 json
  • 谢谢塔马斯,我已经更新了。

标签: javascript angularjs json d3.js c3.js


【解决方案1】:

实际上,您的键枚举数组必须匹配包含值的 JSON 键:

替换:

[{"Type":"Dog","Number":13},{"Type":"Cat","Number":21}]

作者:

[{"Dog":13, "Cat":21}, {"Dog":42, "Cat":31}, ...]

注意:您可以考虑使用小写键以避免错误。

编辑:这是您的控制器的外观

angular.module('c3example', [])
  .controller('ExampleCtrl', function($http, $scope) {
    $http.get('chartData.json')    // Use angular $http instead of d3.json to use promise chaining
      .then(function ( json ) {
        $scope.data = formatData(json.data);  // format received data

        // generate chart
        $scope.chart_types = c3.generate({
          bindto: d3.select('#chart'),
          size: {
            weight: 640,
            height: 480
          },
          data: {
            json: $scope.data,
            keys: {
              value: ['Dog', 'Cat'],
            },
            type: 'bar'
          },
          bar: {
            width: {
              ratio: 0.5 
            }
          }
        });
      },
      function ( err ) {
        console.log(err);   // log if an error occurs
      });

    // function that take you raw data into input and return a c3 compatible array
    function formatData ( json ) {
      var formattedData = [],
          object        = {};

      // fill object with data
      angular.forEach(json, function(row) {
        if (row.hasOwnProperty('Type') && row.hasOwnProperty('Number')) {
          this[row.Type] = row.Number;
        }
      },object);

      formattedData.push(object); // push c3 object in the array

      return formattedData;
    }
  })

【讨论】:

  • 那太好了,但我无法更改数据结构:(
  • hmm.. 所以你必须在使用之前对其进行转换。一旦我弄清楚如何,我会更新我的答案。
猜你喜欢
  • 2015-12-04
  • 2015-02-26
  • 2019-06-15
  • 2016-06-07
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多