我正在尝试使用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/[email protected]/dist/leaflet.js"></script>
<link href="https://unpkg.com/[email protected]/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>
但是当我刷新浏览器时,我得到的是具有第一个值的直方图:
我在数据集设置中尝试了一个for循环,但是chart.js不喜欢它。如何让chart.js显示数组中的所有值?
您需要在外部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>