[英]How can I plot data from an external JSON file to a chart.js graph?
我想使用chart.js從外部JSON文件中繪制數據。 例如, 這里的json文件列出了電影(“標題”)和評級(“rt_score”)。 我希望能夠顯示每部電影及其評級,而不在.js文件中包含靜態JSON,而是使用$ .ajax調用方法來引用/ films端點。
我想:
labels:labelsVariable data:dataVariable
到目前為止, 這是靜態數據的設置。
這是我的HTML:
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js">
</script>
</body>
這里是成功生成我想要的條形圖的js,但在“labels”和“data”中使用靜態數據而不是引用JSON文件。
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Castle in the Sky', 'Grave of the Fireflies'],
datasets: [{
label: 'rating',
data: [95, 97],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
而不是使用靜態數據和標簽,如何使用$ .ajax調用方法引用外部JSON文件?
基於我所讀到的,我可能必須使用“map”將對象分解為包含標簽和數據的數組?
先感謝您。
動態加載json圖表數據,並在創建圖表時進行設置。 您可以通過多種方式加載圖表json數據。 但是,我相信JQuery getJSON
函數與您更相關。
$.getJSON( "chartdata/test.json", function( data ) {
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
我認為您正在尋找Ajax請求來填充您的圖表。
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var ctx_live = document.getElementById("mycanvas");
var myChart = new Chart(ctx_live, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 1,
borderColor:'#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Chart.js - Dynamically Update Chart Via Ajax Requests",
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
var postId = 1;
var getData = function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/' + postId + '/comments',
success: function(data) {
myChart.data.labels.push("Post " + postId++);
myChart.data.datasets[0].data.push(getRandomIntInclusive(1, 25));
// re-render the chart
myChart.update();
}
});
};
setInterval(getData, 3000);
看這里的實例。
我想到了。 這是有效的。 我必須使用.map在變量中正確設置數據,然后將這些變量用作數據和標簽。
function renderChart(data, labels) {
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'This week',
data: data,
}]
},
});
}
function getChartData() {
$("#loadingMessage").html('<img src="./giphy.gif" alt="" srcset="">');
$.ajax({
url: "https://ghibliapi.herokuapp.com/films",
success: function (result) {
var data = result.map(x=>x.rt_score);
var labels = result.map(x=>x.title);
renderChart(data, labels);
console.log(data);
},
});
$("#renderBtn").click(
function () {
getChartData();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.