https://plnkr.co/edit/O4BxVsdOZBc4R68p
fetch(target)
.then(response => response.json())
.then(data => {
var prices = data['Time Series (5min)'];
for (prop in prices) {
var stockPrices = prices[prop]['1. open'];
//change to 2. high, etc
console.log(`${prop} : ${stockPrices}`);
stocksData.datasets[0].data.push({x: prop, y: +stockPrices})
//time x axes are preventing render
window.lineChart.update();
}
})
我正在从 AlphaVantage API 获取信息,并尝试将时间绘制为 X 轴,将开盘价绘制为 Y 轴。然而,来自 API 的时间格式很奇怪,并且没有显示为图表。我研究过 Moment.js,但这似乎是在浪费时间,而不是格式化它们。谁能给我一些有关正确绘制时间的指示?
最佳答案
您的问题来自两件事:
- 您的图表配置中带有
xAxes
的选项应改为xAxis
- 图表数据中缺少标签且数据正确
以下是有效的代码:
var stocksData = {
datasets: [
{
label: 'open',
backgroundColor: 'rgba(104,0,255,0.1)',
data: [
],
},
],
};
window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
var lineChart = new Chart(ctx, {
type: 'line',
data: stocksData,
options: {
scales: {
xAxis: [
{
type: 'linear',
position: 'bottom',
},
],
},
},
});
window.lineChart = lineChart;
};
var sym = 'AAPL'; //get from form
var tseries = 'TIME_SERIES_INTRADAY'; //get from form
var target = `https://www.alphavantage.co/query?function=${tseries}&symbol=${sym}&interval=5min&apikey=VA3RZ8B9PPYWKQKN`;
function update () {
fetch(target)
.then(response => response.json())
.then(data => {
var prices = data['Time Series (5min)'];
for (prop in prices) {
var stockPrices = prices[prop]['1. open'];
//change to 2. high, etc
console.log(`${prop} : ${stockPrices}`);
//stocksData.datasets[0].data.push({x: prop, y: +stockPrices})
stocksData.datasets[0].data.push(stockPrices);
// Format date here. For example with Moment:
// var date = moment(prop).format('YYYY-MM-DD')
stocksData.labels.push(prop);
//time x axes are preventing render
window.lineChart.update();
}
})
.catch(error => console.error(error));
}
图表数据的完整格式如下:
var stocksData = {
labels: ['date1', 'date2', 'date3', 'date4'],
datasets: [
{
label: 'open',
backgroundColor: 'rgba(104,0,255,0.1)',
data: [
'data1', 'data2', 'data3', 'data4'
],
},
],
};
然后每个数据和日期标签应该分别推送:
stocksData.datasets[0].data.push(stockPrices);
stocksData.labels.push(prop);
要使用 Moment 进行格式化,您可以使用:
var dateStr = moment(prop).format('YYYY-MM-DD');
关于javascript - 如何将来自外部源的时间作为 X 轴添加到 ChartJS 图表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60697531/