Library

[Chart.js] Y์ถ• ์ตœ๋Œ€๊ฐ’ ๋™์ ์œผ๋กœ ์„ค์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•

yuri lee 2023. 6. 28. 23:02
๋ฐ˜์‘ํ˜•

Intro

 ์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” Chart.js์—์„œ Y์ถ• ์ตœ๋Œ€๊ฐ’์„ ๋™์ ์œผ๋กœ ์„ค์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

Case

์šฐ์„  Chart ์ปดํฌ๋„ŒํŠธ๋ฅผ ํ™œ์šฉํ•˜๋Š” ๋ถ€๋ถ„์€ ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค. option์— ๋”ฐ๋ผ ํ‘œ์‹œํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค๋ฅด๊ฒŒ retrun ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.  ๋ฐ์ดํ„ฐ๊ฐ€ ๋™์ ์œผ๋กœ ๋‹ฌ๋ผ์ง€๋‹ค ๋ณด๋‹ˆ y์ถ• ๋ฒ”์œ„ ์ตœ๋Œ€๊ฐ’๋„ ํ•ด๋‹น datasets์— ๋งž๊ฒŒ ๋‹ค๋ฅด๊ฒŒ ํ‘œ์‹œํ•ด์•ผ ํ–ˆ์Šต๋‹ˆ๋‹ค. 

const getData = (option: string): ChartData<'line'>['datasets'] => {
    if (option === 'hourly') {
      return [
        {
          fill: false,
 		  ..., 
          data: [0, 150, 180, 270, 210, 160, 160, 202, 265, 210, 270, 255, 290, 360, 375, 160, 202, 265, 210, 270, 255, 290, 360, 375]
        },
        {
          fill: false,
          ..., 
          data: [50, 125, 105, 130, 215, 195, 140, 160, 230, 300, 220, 170, 210, 200, 280, 140, 160, 230, 300, 220, 170, 210, 200, 280]
        },
        {
          fill: false,
          ..., 
          data: [20, 99, 82, 90, 115, 115, 74, 75, 130, 155, 125, 90, 140, 130, 180, 74, 75, 130, 155, 125, 90, 140, 130, 180]
        }
      ]
    } else if (option === 'daily') {
      return [
        {
          fill: false,
          ..., 
          data: [20, 99, 82, 90, 115, 115, 74, 75, 130, 155, 125, 90, 20, 99, 82, 90, 115, 115, 74, 75, 130, 155, 125, 90, 100, 400, 130, 155, 125, 90]
        }
      ]
    } else {
      return [
        {
          fill: false,
          ..., 
          data: [20, 99, 82, 90, 115, 115, 74, 75, 130, 155, 125, 90]
        }
      ]
    }
}
const data: ChartData<'line'> = {
    labels: getLabel(option),
    datasets: getData(option)
}
<LineChart data={data} height={400} options={options} />

 

How to dynamically set y-axis max value

์ด๋ฅผ ์œ„ํ•ด ์ €๋Š” ๋‹ค์Œ์˜ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜์˜€๋Š”๋ฐ์š”, suggestedMax ์†์„ฑ์„ ํ™œ์šฉํ•˜์—ฌ getData()๋ฅผ ํ˜ธ์ถœํ•˜๊ณ , dataset์˜ data๋ฅผ flatMap() ๋ฉ”์„œ๋“œ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ชจ๋‘ ํ‰ํƒ„ํ™”๋ฅผ ํ•ด์คฌ์Šต๋‹ˆ๋‹ค. ์ดํ›„ ๋ฐฐ์—ด ์•ˆ์—์„œ ๊ฐ€์žฅ ํฐ ์ˆซ์ž๋ฅผ ๋ฝ‘์•„์„œ (Math.max) suggestedMax ์— ๋„ฃ์–ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค. 

const options: ChartOptions<'line'> = {
    scales: {
      ..., 
      y: {
        min: 0,
        suggestedMax: Math.max(
          ...getData(option)
            .flatMap(dataset => dataset.data)
            .filter((value): value is number => value !== null)
        ),
       	..., 
      }
    },
   	...
}

 

์œ„์˜ ๋ฐฉ๋ฒ•์„ ํ™œ์šฉํ•˜๋ฉด Y์ถ• ์ตœ๋Œ€๊ฐ’์„ ๋™์ ์œผ๋กœ ์„ค์ •ํ•˜์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค .

๋ฐ˜์‘ํ˜•

'Library' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Chart.js] line ์ฐจํŠธ border line ๊ตต๊ฒŒ ์ง€์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•  (0) 2023.08.11