简体   繁体   English

C3.js将条形图与外部json数据分组

[英]C3.js grouped bar chart with external json data

I have the following json data: 我有以下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,
  },
 }
}

And I am trying to make a grouped C3 bar chart with male and female for each age range, but haven't had any luck. 而且我正在尝试制作每个年龄段的男性和女性成组的C3条形图,但是没有任何运气。 What am I missing? 我想念什么?

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,
  }},
});

A couple of different ways: 几种不同的方式:

  1. Format your json so each point on the xaxis and its values are a separate entry in an array. 格式化json,以便xaxis上的每个点及其值都是数组中的单独条目。 Set 'x' in data.keys to pick the category attribute out of the data ('name' here) 在data.keys中设置“ x”以从数据中选择类别属性(此处为“ name”)

http://jsfiddle.net/38cqjqnu/1/ 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. Turn the data into two arrays, male and female. 将数据分为两个数组,男性和女性。 The categories must be set explicitly in the axis declaration. 必须在轴声明中显式设置类别。

http://jsfiddle.net/rgbw1pL0/1/ 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'],
  }},

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM