Chart.js - 将数据集中的数据绑定到特定的图表标签

时间:2018-04-13 10:30:52

标签: javascript charts chart.js country

我正在尝试在Chart.js中创建一个输出世界人口的图表(这只是我将用于另一个项目的一个例子),我的问题是其中一个国家没有& #39; t有一个人口(Somethingistan),我确实希望这个国家能够立即上市,但是我想要人口来“跳过”#39;它有没有办法做到这一点?

这是我制作我的图表

new Chart(document.getElementById("bar-chart"), {
    type: 'bar',
    data: {
        labels: ["Africa", "Asia", "Europe", "Somethingistan", "North America"],
        datasets: [
            {
                label: "Population (millions)",
                backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
                data: [2478,5267,734,784,433]
            }
        ]
    },
    options: {
        legend: { display: false },
        title: {
            display: true,
            text: 'Predicted world population (millions) in 2050'
        }
    }
});

我也尝试过这种方法:

data: [{x:"Africe", y:2478},{x:"Asia", y:5267},{x:"Europa", y:734},{x:"North America", y:784}]

但我认为它不会起作用,但基本上这就是我想要实现的,将数据绑定到特定标签。

1 个答案:

答案 0 :(得分:0)

绘制图表时,需要两个数组 - > labels& data

每个数组应具有相同数量的元素,
data数组中的第一个元素将被"绑定"到labels数组

中的第一个标签

如果标签没有值,请使用null

labels: ['Africa', 'Asia', 'Europe', 'Somethingistan', 'North America']

data: [2478,5267,734,null,784]

在上面的代码段中,

2478将绑定'Africa'
null将绑定到'Somethingistan'

请参阅以下工作代码段...



window.onload = function () {
  new Chart(document.getElementById('bar-chart'), {
    type: 'bar',
    data: {
      labels: ['Africa', 'Asia', 'Europe', 'Somethingistan', 'North America'],
      datasets: [{
        label: 'Population (millions)',
        backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f','#e8c3b9','#c45850'],
        data: [2478,5267,734,null,784]
      }]
    },
    options: {
      legend: {
        display: false
      },
      title: {
        display: true,
        text: 'Predicted world population (millions) in 2050'
      }
    }
  });
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<div class="container">
  <canvas id="bar-chart"></canvas>
<div>
&#13;
&#13;
&#13;