Framework/React

[React] react + typescript + Chart.js Multi-Axis ์„ค์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•

yuri lee 2023. 7. 25. 23:54
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”.  ์•ž์„  ํฌ์ŠคํŒ…์—์„œ Multi type chart๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ดค๋Š”๋ฐ์š”, ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” Chart.js์—์„œ Multi-Axis ๋ฅผ ์„ค์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. Multi-Axis ์€ ๋ฐ์ดํ„ฐ์˜ ๋‹จ์œ„ ์ฐจ์ด๊ฐ€ ์ปค์„œ ํ•œ๊บผ๋ฒˆ์— ํ‘œํ˜„ํ•  ๋•Œ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค. 

 

How to do

 ์ œ ๊ฒฝ์šฐ series1, series2 ๋‘ ๋ฐ์ดํ„ฐ์— ์ƒ์‘๋˜๋Š” y์ถ•์„ ์˜ค๋ฅธ์ชฝ๊ณผ ์™ผ์ชฝ์— ํ‘œ์‹œํ•˜๊ณ  ์‹ถ์—ˆ์Šต๋‹ˆ๋‹ค.

 

๊ฐ๊ฐ ์‚ฌ์šฉํ•˜๊ณ ์ž ํ•˜๋Š” ์ถ•์ด ๋‹ค๋ฅด๊ธฐ ๋•Œ๋ฌธ์— yAxisID ์†์„ฑ์„ ํ™œ์šฉํ•˜์—ฌ a, b ๋‘๊ฐœ๋ฅผ ์ง€์ •ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ดํ›„ options์—์„œ ํ•ด๋‹น yAxisID๋ฅผ ์‚ฌ์šฉํ•ด position์„ right, left๋กœ ์„ค์ •ํ•ด์คฌ์Šต๋‹ˆ๋‹ค.

  const series1: number[] = []
  const series2: number[] = []

  data.forEach(temp => {
      // Insert data
  })

  const datasets: ChartDataset<'line' | 'bar', number[]>[] = [
    {
      type: 'line',
      label: 'A',
      yAxisID: 'y-axis-a',
      borderColor: 'white',
      borderWidth: 2,
      fill: false,
      pointRadius: 0,
      data: series3
    },
    {
      type: 'bar',
      label: 'B',
      yAxisID: 'y-axis-b',
      backgroundColor: 'red',
      data: series1
    }
  ]


  const options: ChartOptions<'line' | 'bar'> = {
    plugins: {
     ...
    },
    scales: {
      'y-axis-a': {
        type: 'linear',
        position: 'right',
        grid: {
          display: false
        }
      },
      'y-axis-b': {
        type: 'linear',
        position: 'left',
        grid: {
          display: false
        }
      }
    }
  }

  const chartData: ChartData<'line' | 'bar', number[], string> = {
    labels,
    datasets
  }

 

๋ณ€์ˆ˜๋ช…์ด๋‚˜ ์œ„์น˜๋Š” ์ผ€์ด์Šค์— ๋งž๊ฒŒ ์‚ฌ์šฉํ•˜์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค :)

๋ฐ˜์‘ํ˜•