C3.js使用外部json数据对条形图进行分组

时间:2017-03-20 17:53:05

标签: javascript json c3.js

我有以下json数据:

var data = {
age:
  {
 male:
 { '0-9': 249.8740575482693,
   '10-19': 238.2744788358169,
   '20-29': 369.10362988529357,
   '30-39': 156.9635033529556,
   },
 female:
 { '0-9': 182.36397053287214,
   '10-19': 265.8954005792933,
   '20-29': 210.98459487382183,
   '30-39': 159.24536288458913,
  },
 }
}

我正在努力为每个年龄段制作一个男女分组的C3条形图,但是没有运气。我错过了什么?

var sex = ['male', 'female'];

var chart = c3.generate({
    bindto: '#chart2',
  data: {
    json: [data["age"]],
    keys: {
     value: ['0-9', '10-19', '20-29', '30-39']
   },
    type: 'bar',
  },

  axis: { x: {
    type: 'category',
    categories: sex,
  }},
});

1 个答案:

答案 0 :(得分:1)

有两种不同的方式:

  1. 格式化您的json,以便xaxis上的每个点及其值都是数组中的单独条目。设置' x'在data.keys中从数据中选择category属性(' name' here)
  2. http://jsfiddle.net/38cqjqnu/1/

    var data = {
    age: [
       {name: "0-9", male: 249.8740575482693, female: 182.36397053287214},
       {name: "10-19", male: 238.2744788358169, female: 265.8954005792933},
       {name: "20-29", male:  369.10362988529357, female: 210.98459487382183},
       {name: "30-39", male: 156.9635033529556, female: 159.24536288458913},
    ]
    };
    
    var chart = c3.generate({
        bindto: '#chart',
      data: {
        json: data["age"],
        keys: {
         value: ["male","female"],
            x: "name",
       },
        type: 'bar',
      },
      axis: { x: {
                type: "category"
      }},
    });
    
    1. 将数据转换为两个数组,男性和女性。必须在轴声明中明确设置类别。
    2. http://jsfiddle.net/rgbw1pL0/1/

      var data = {
      age:
        {
       male:
      [249.8740575482693,
          238.2744788358169,
         369.10362988529357,
        156.9635033529556,
         ],
       female:
       [  182.36397053287214,
          265.8954005792933,
          210.98459487382183,
         159.24536288458913,
        ],
       }
      }
      
      var chart = c3.generate({
          bindto: '#chart',
        data: {
          json: data["age"],
          type: 'bar',
        },
        axis: { x: {
                  type: "category",
            categories: ['0-9','10-19','20-29','30-39'],
        }},
      
      });