[React] React에서 chartJs data label 추가하기
https://mingmeng030.tistory.com/266
[React] React+typescript에서 chartJs의 update() 사용법
프로젝트를 할 때마다 그래프가 필요할 때 라이브러리 ‘chartJs’의 Bar chart를 사용하였는데, 그냥 javascript가 아닌 react+typescript 환경에서 사용할 때 상태 변경에서 문제가 발생했다. react+typescript
mingmeng030.tistory.com
기존에 적용한 chartjs에 data label이 바로 보이도록 추가하고 싶은 경우가 있다.
default 로는 아래처럼 data label이 보이지 않다가
마우스가 hover 되었을 때 그래프 위에 툴팁으로 뜬다.
만약 위와 달리 아래처럼 hover 없이도 data label이 고정되어 보이게 하고 싶다면 어떻게 해야할까?
chartjs-plugin-datalabels 이라는 plugin 을 설치한다.
npm install chartjs-plugin-datalabels --save
chartjs 라이브러리를 사용하는 컴포넌트 상단에 plugin을 import 한다.
import ChartDataLabels from "chartjs-plugin-datalabels";
기존 코드의 option > plugins 내부에 datalabels 를 작성한다.
chartRef.current = new Chart(ctx, {
plugins: [ChartDataLabels],
type: "bar",
data: statisticsData,
options: {
responsive: false,
plugins: {
legend: { ... },
datalabels: {
formatter: function (value) {
if (value == 0) return "";
else return value + "시간";
},
display: true,
color: "black",
anchor: "end",
align: "start",
},
},
indexAxis: "y",
scales: {
x: { ... },
y: { ... },
},
},
});
datalabels
datalabels: {
formatter: function (value) {
// data가 0인 경우 label을 표시하지 않는다.
if (value == 0) return "";
else return value + "시간";
},
display: true,
color: "black",
anchor: "end",
align: "start",
},
formatter : 위에서 data 로 넣어준 배열에서 필요한 값을 뽑아내 보여주고 싶은 형태로 조작한다.
예시 : 각 데이터의 index와 value를 함께 보여주는 formatter
formatter: function (value, context) {
// 각 데이터의 인덱스
var idx = context.dataIndex;
// 화면에 보여줄 텍스트
return context.chart.data.labels[idx] + value + '%';
},
display, color, anchor, align 이외에도 많은 option이 있으니 아래 공식 사이트를 참고하자.
https://chartjs-plugin-datalabels.netlify.app/guide/options.html#scriptable-options