图表js条形图未显示数组

时间:2019-02-18 16:06:16

标签: javascript chart.js

我正在尝试使用chart.js创建条形图

我的代码如下:

var myBarChart = new Chart(histChart, {
  type: "bar",
  data: {
    datasets: [{
      data: [28, 6, 2, 4, 2, 2, 1, 0, 0, 1]
    }]
  }
});
body {
  margin: 0;
  padding: 0;
}

#histChart {
  width: 600px;
  height: 480px;
  border: 3px solid #8AC007;
}
<!-- Include Leaflet -->
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" rel="stylesheet">
<!-- Include CARTO.js -->
<script src="https://libs.cartocdn.com/carto.js/v4.1.10/carto.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/13.1.0/nouislider.min.js"></script>
<link href="https://carto.com/developers/carto-js/examples/maps/public/style.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/13.1.0/nouislider.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>

<body>
  <canvas id="histChart" width="400" height="100"></canvas>

</body>

但是当我刷新浏览器时,我得到的只是一个带有第一个值的直方图:

enter image description here

我在数据集设置中尝试了for循环,但是chart.js不喜欢它。如何获取chart.js以显示数组中的所有值?

1 个答案:

答案 0 :(得分:0)

您需要在外部labels对象上添加data属性。这对应于每个数据集中的每个数据点。例如,有28个映射到“红色”,依此类推。

您可以看到Creating a Chart以获得更好的示例

var myBarChart = new Chart(histChart, {
  type: "bar",
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: "Favorite Color",
      data: [28, 6, 2, 4, 2, 2]
    }]
  }
});
body {
  margin: 0;
  padding: 0;
}

#histChart {
  width: 600px;
  height: 480px;
  border: 3px solid #8AC007;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>

<body>
  <canvas id="histChart" width="400" height="100"></canvas>
</body>