我正在使用Chart.js绘制简单的折线图。一切看起来不错,我从API获取数据,但无法在折线图中显示:
$.ajax({
url: "https://api.thevirustracker.com/free-api?countryTimeline=PK",
dataType: 'json',
success: function(result) {
const datachart = []
console.log("datachart", datachart)
for (var i = 0, l = result.timelineitems.length; i < l; i++) {
const entries = result.timelineitems[i]
const x = Object.keys(entries);
const y = Object.values(entries)
// const y = [2,2,4,7,5,4,7,4,1,0,7,4,8,5,44,1,44,111,44,1,11,1,77,88,55,22,99,66,55,77,44,55,22,00,44,77,8,9,5,7,4,1]
datachart.push({
y: y,
x: x
})
}
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
datasets: [{
data: datachart,
label: ["datachart[1]"],
borderColor: "#18bc9c",
fill: false
}]
},
// Configuration options go here
options: {}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="myChart" width="200" height="200"></canvas>
我想添加一个x变量数组作为标签,数据要添加Object.values(entries).new_daily_cases
作为要显示的数据
data.labels
,则可以将单个数据集的data
定义为值的数组。请在下面查看您的修改后的代码:
$.ajax({
url: "https://api.thevirustracker.com/free-api?countryTimeline=PK",
dataType: 'json',
success: result => {
const rawData = result.timelineitems[0];
delete rawData.stat;
const labels = Object.keys(rawData);
const data = Object.values(rawData);
var chart = new Chart(document.getElementById('myChart'), {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'New Daily Cases',
data: data.map(o => o.new_daily_cases),
borderColor: "violet",
fill: false
},
{
label: 'New Daily Deaths',
data: data.map(o => o.new_daily_deaths),
borderColor: "orange",
fill: false
},
{
label: 'Total Cases',
data: data.map(o => o.total_cases),
borderColor: "blue",
fill: false
},
{
label: 'Total recoveries',
data: data.map(o => o.total_recoveries),
borderColor: "green",
fill: false
},
{
label: 'Total Deaths',
data: data.map(o => o.total_deaths),
borderColor: "red",
fill: false
}]
},
options: {}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>