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');
“奇数”时间格式是标准almost的(international datetime format)。在这种情况下为YYYY-MM-DD HH:MM:SS
。我强烈建议您熟悉它,并优先于DD/MM/YYYY
或MM/DD/YYYY
使用它。
您可以通过将x轴类型更改为time
并添加适当的configuration options来修正代码:
options: {
scales: {
xAxes: [
{
type: 'time',
...
请注意,您还需要将对Chart.js的调用更改为version with moment.js bundled(或单独添加力矩):
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>