develop
PublishDate29 Sep 2023
Implementing a Gauge Chart with Chart.js

The gauge chart I needed to implement is designed in a half donut shape, with a gradient from green to yellow to red, and it displays a number in the center. Since my development environment is TypeScript and React, I used Chart.js and react-chartjs-2 for this project.

ChartImage

Getting Started with Chart.js

I referred to the documentation of Chart.js and react-chartjs-2 to implement the chart.

import { Chart as ChartJS, ArcElement } from "chart.js";
import { Pie } from "react-chartjs-2";
ChartJS.register(ArcElement);
const GaugeChart = () => {
const data = {
datasets: [
{
label: 'Chart',
data: [12, 19],
backgroundColor: [
...
],
borderWidth: 0,
},
],
};
return (
<Pie data={data}/>
);
}
import { Chart as ChartJS, ArcElement } from "chart.js";
import { Chart as ChartJS, ArcElement } from "chart.js";
const xCoor = chart.getDatasetMeta(0).data[0].x;
const xCoor = chart.getDatasetMeta(0).data[0].x;

Since there wasn’t a specific option for a half donut chart, I considered which graph to use and decided to go with a pie chart.

circumference, rotation 코드를 추가하면 pie가 half pie가 됩니다. 여기에 cutout 설정하면 half donut 모양이 됩니다.

To update the chart values based on the data received from the API, I modified the static data value. For testing purposes, I used placeholder values.

To display the current value in the center of the gauge chart, I applied additional configurations. Some finer design details were implemented using CSS and options provided by chart.js.

Actually…

I used chart.js to implement the chart, but I also tried d3 and apexcharts. Using these different libraries helped me change my perspective on charts, which I used to find difficult. It was a good learning experience. I also thought a lot about how to add animations to the chart, but since these libraries provide animation features by default, I was able to implement it easily.


References

© 2024

Park Gadan

33°06'56.2"-38°34'03.5"