iT邦幫忙

2021 iThome 鐵人賽

DAY 4
0
Modern Web

用React刻自己的投資Dashboard系列 第 4

用React刻自己的投資Dashboard Day4 - highcharts製作線圖

tags: 2021鐵人賽 React

Javascript繪圖套件

在搜尋chart library的時候,發現JS可以用的library很多,包含 D3.js / highcharts / Google Charts / Chart.js / chartist.js / recharts / n3-charts / Plotly.js / canvasJS,研究一下發現highcharts的網站有Stock chart的demo,算是蠻好入手開始研究的,就先從這個套件開始學習。

資料來源

投資數據的其中一個項目是總體經濟的數據,透過觀察總體經濟數據可以知道目前的經濟狀況相對於歷史紀錄是在什麼樣的位階,因此第一個圖表使用美國FRED提供的消費者物價指數來繪圖。

FRED其實有提供API可以直接串接資料,不過為了循序漸進,我這邊會先將資料存成靜態檔案,先以highcharts套件的應用為主,畫好圖之後,再來討論API的串接以及資料的更新。

靜態資料放置位置在Charts components內,這邊就是先暫存,稍後串接API後就會刪除掉,先以JSON的方式存檔。

dummyData.json

{
  "TREAST": {
    "title": "聯準會持有美債金額",
    "document": "The total face value of U.S. Treasury securities held by the Federal Reserve. This total is broken out in the lines below. Purchases or sales of U.S. Treasury securities by the Federal Reserve Bank of New York (FRBNY) are made in the secondary market, or with various foreign official and international organizations that maintain accounts at the Federal Reserve. FRBNY's purchases or sales in the secondary market are conducted only through primary dealers.",
    "source": "FRED",
    "units": "百萬美元",
    "latest_released_date": "2021-08-06",
    "next_updated_date": "2021-08-13",
    "frequency": "weekly",
    "data": {
      "realtime_start": "2021-08-10",
      "realtime_end": "2021-08-10",
      "observation_start": "2021-01-01",
      "observation_end": "2021-08-10",
      "units": "lin",
      "output_type": 1,
      "file_type": "json",
      "order_by": "observation_date",
      "sort_order": "asc",
      "count": 31,
      "offset": 0,
      "limit": 100000,
      "observations": [
        {
          "realtime_start": "2021-08-10",
          "realtime_end": "2021-08-10",
          "date": "2021-01-06",
          "value": "4699421.0"
        },
        {
          "realtime_start": "2021-08-10",
          "realtime_end": "2021-08-10",
          "date": "2021-01-13",
          "value": "4723733.0"
        },
        {
          "realtime_start": "2021-08-10",
          "realtime_end": "2021-08-10",
          "date": "2021-01-20",
          "value": "4743552.0"
        },
        ...
      ]
    }
  }
}

The official Highcharts supported wrapper for React

Highcharts官方有專門針對React設計一個wrapper,叫做highcharts-react,讓開發者可以很輕鬆import套件開始製圖。只要三個步驟就可以繪圖完成

  1. 照著官方的說明進行安裝
npm install highcharts highcharts-react-official
  1. 在React元件內匯入套件
import Highcharts from 'highcharts/highstock';
import HighchartsReact from 'highcharts-react-official';
  1. 將資料導入並設定好options即可繪出圖形,完整程式碼如下

Charts.js

import React from 'react';
import styles from './Chart.module.css';
import { Row, Col } from 'react-bootstrap';
// highcharts react components
import Highcharts from 'highcharts/highstock';
import HighchartsReact from 'highcharts-react-official';
// dummy data
import dummyData from './dummyData.json';

// get information of chart
const chartElementInfo = () => {
  // chart data
  const chartData = [];
  dummyData.TREAST.data.observations.forEach(ob => {
    chartData.push([new Date(ob.date).getTime(), Number(ob.value)]);
  });

  return {
    document: dummyData.TREAST.document,
    source: dummyData.TREAST.source,
    updated: dummyData.TREAST.latest_released_date,
    options: {
      title: {
        text: dummyData.TREAST.title
      },
      series: [
        {
          name: dummyData.TREAST.title,
          data: chartData
        }
      ],
      xAxis: {
        type: "datetime",
        title: {
          text: 'Date'
        }
      }
    }
  }
};

const Charts = () => {
  return (
    <Row className={styles.charts}>
      <Col sm={12} md={6} lg={4} className={styles.chartItem}>
        <HighchartsReact
          highcharts={Highcharts}
          constructorType={'stockChart'}
          options={chartElementInfo().options}
        />
        <div className={styles.chartInfo}>
          <p className={styles.source}>source: {chartElementInfo.source}</p>
          <p className={styles.date}>updated: {chartElementInfo.updated}</p>
        </div>
        <div>
          <p className={styles.document}>{chartElementInfo.document}</p>
        </div>
      </Col>
    </Row>
  )
};

export default Charts;
  1. 繪圖成果

產出可以手動調整時間的互動式圖表,使用者可以選擇自己要看的區間去更動資料範圍,圖也會隨之改變。

本篇小結

本篇使用highchart串接靜態資料產出圖表,目前這個頁面只有一張圖,接下要實作同一個頁面很多張圖的情況,並盡量讓頁面載入的速度保持穩定。


上一篇
用React刻自己的投資Dashboard Day3 - React專案初始架構
下一篇
用React刻自己的投資Dashboard Day5 - 多張圖表渲染(Rendering lists)
系列文
用React刻自己的投資Dashboard30

尚未有邦友留言

立即登入留言