我正在尝试通过Javascript在JsFiddle上创建图表。 这是我的代码。
$(document).ready(function() {
var dataPointsA = []
var dataPointsB = []
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/12qook',
dataType: 'json',
success: function(field) {
for (var i = 0; i < field.length; i++) {
dataPointsA.push({
x: field[i].userId,
y: field[i].numberOfusers
});
}
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "User Count"
},
data: [{
type: "line",
name: "line1",
dataPoints: dataPointsA
}]
});
chart.render();
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><br>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
我对此并不陌生,所以您能告诉我我的代码有什么问题吗?谢谢
答案 0 :(得分:2)
如果要呈现分类数据,请通过将type
更改为column
,将x
更改为label
,使用条形图而不是折线图:
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/12qook',
dataType: 'json',
success(data) {
new CanvasJS.Chart("chartContainer", {
title: {
text: "User Count"
},
data: [{
type: "column",
dataPoints: data.map(
({ userId, numberOfusers }) => ({ label: userId, y: numberOfusers })
)
}]
}).render();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><br>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>