簡體   English   中英

Chart.js中帶有JSON數據的堆疊條形圖

[英]Stacked bar charts in Chart.js with JSON data

我有以下JSON數據。

[
  {
      "date": "2016-05-01T00:00:00",
      "productInformation": [
        {
            "productName": "Apple",
            "totalWeight": 200
        }
      ]
  },
  {
      "date": "2016-09-01T00:00:00",
      "productInformation": [
        {
            "productName": "Apple",
            "totalWeight": 632
        },
        {
            "productName": "Mango",
            "totalWeight": 856
        },
        {
            "productName": "Spinach",
            "totalWeight": 545
        },
        {
            "productName": "Grapes",
            "totalWeight": 338
        }
      ]
  },
  {
      "date": "2017-01-01T00:00:00",
      "productInformation": [
        {
            "productName": "Mango",
            "totalWeight": 500
        }
      ]
  }
]

在X軸上,我想顯示月份和年份,在Y軸上,我想顯示堆疊的產品信息欄。 例如在2016-05年度只有Apple,因此只會顯示Apple。 在2016-09年,有4個產品,因此將根據4個產品及其總重量來顯示4個樁欄。 我已經閱讀了chart.js文檔。 根據文檔,我必須在數據集中提供Y軸值。 如何為數據集提取Y軸值,以根據給定的JSON數據創建堆疊的條形圖? 如果我想根據上面給出的JSON數據手動創建圖表,則可能是這樣。

var barChartData = {
labels: ["May 2016", "September 2016", "January 2017"],
datasets: [{
    label: "Apple",
    data: [200, 632, 0],
    backgroundColor: "#3c8dbc"
},
{
    label: "Mango",
    data: [0,856,500],
    backgroundColor: "#3c8dbc"
},
{
    label: "Spinach",
    data: [0,545,0],
    backgroundColor: "#3c8dbc"
},
{
    label: "Grapes",
    data: [0,338,0],
    backgroundColor: "#3c8dbc"
}]
};

我需要一種從給定的JSON數據中提取data集的data部分的方法。

此代碼段應解決您問題的最困難部分(使用ES6語法):

 const data = [{ "date": "2016-05-01T00:00:00", "productInformation": [{ "productName": "Apple", "totalWeight": 200 }] }, { "date": "2016-09-01T00:00:00", "productInformation": [{ "productName": "Apple", "totalWeight": 632 }, { "productName": "Mango", "totalWeight": 856 }, { "productName": "Spinach", "totalWeight": 545 }, { "productName": "Grapes", "totalWeight": 338 }] }, { "date": "2017-01-01T00:00:00", "productInformation": [{ "productName": "Mango", "totalWeight": 500 }] }] const uniq = a => [...new Set(a)] const flatten = a => [].concat.apply([], a) // step 1: find the distinct dates: ["2016-05-01T00:00:00", ... ] const dates = data.map(e => e.date) // step 2: find the distinct labels: [Apple, Mango, ... ] const labels = uniq( flatten(data.map(e => e.productInformation)) .map(e => e.productName)) // step 3: map the labels to entries containing their data by searching the original data array const result = labels.map(label => { return { label, data: dates.map(date => { const hit = data.find(e => e.date === date) .productInformation .find(p => p.productName === label) return hit ? hit.totalWeight : 0 }) } }) console.log(result) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM