どのように私はChartJSグラフにX軸などの外部ソースから供給時間を追加できますか?

アーロン :

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に見ているが、それはそれらのフォーマットではない、時間を作っているように見えます。誰もが正しい時刻をグラフに私に任意のポインタを与えることはできますか?

KeitelDOG:

あなたの問題は、2つのことから来ています:

  1. オプションであなたのチャートの設定xAxesそれはする必要がありますxAxis代わりに、
  2. チャートデータでのラベルと、正しいデータがありません

ここで働くのコードは次のとおりです。

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);

あなたが使用できる瞬間でフォーマットするには:

var dateStr = moment(prop).format('YYYY-MM-DD');

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=303454&siteId=1