【问题标题】:Chart.js - bind data in dataset to specific chart labelsChart.js - 将数据集中的数据绑定到特定的图表标签
【发布时间】:2018-04-13 10:30:52
【问题描述】:

我正在尝试在 Chart.js 中制作一个输出世界人口的图表(这只是我将用于不同项目的示例),我的问题是其中一个国家没有人口(Somethingistan),我确实希望将国家列在现在的位置,但我想人口“跳过”它,有什么办法吗?

这是我制作图表

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

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

【问题讨论】:

    标签: javascript charts chart.js country


    【解决方案1】:

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

    每个数组应该有相同数量的元素,
    data 数组中的第一个元素,将“绑定”到 labels 数组中的第一个标签

    如果标签没有值,只需使用null

    labels: ['Africa', 'Asia', 'Europe', 'Somethingistan', 'North America']
    
    data: [2478,5267,734,null,784]
    

    在上面的sn-p中,

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

    请参阅以下工作 sn-p...

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 2013-03-31
      • 2014-04-26
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      相关资源
      最近更新 更多