gpt4 book ai didi

javascript - 如何将来自外部来源的时间作为 X 轴添加到 ChartJS 图表中?

转载 作者:行者123 更新时间:2023-12-04 10:24:11 26 4
gpt4 key购买 nike

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/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com