简体   繁体   中英

C3.js grouped bar chart with external json data

I have the following json data:

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. 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. Set 'x' in data.keys to pick the category attribute out of the data ('name' here)

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/

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'],
  }},

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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