vue-chartjs와 chart.js를 이용하여 가로 막대차트를 그려보겠습니다.
(vue 2 버전, chart.js: 3.5.0, vue-chartjs: 3.5.1 버전 사용)
0. 다른 차트 참고
- [Vue.js] Chart.js Doughnut Chart 그리기
- [Vue.js] Chart.js Line Chart 그리기
- [Vue.js] Chart.js Bar Chart 그리기
1. vue-chartjs, chart.js 다운로드
npm install chart.js
npm install vue-chartjs chart.js --save
2. 막대차트 개발 문서(3.5.0 version)
https://www.chartjs.org/docs/3.5.0/charts/bar.html
Bar Chart | Chart.js
Bar Chart A bar chart provides a way of showing data values represented as vertical bars. It is sometimes used to show trend data, and the comparison of multiple data sets side by side. const config = { type: 'bar', data: data, options: { scales: { y: { be
www.chartjs.org
3. 가로 막대차트 구현
3-1. global.js
import { Chart, registerables } from "chart.js";
Chart.register(...registerables);
- 여러 차트와 공유할 수 있는 파일을 global.js로 만들었습니다.
3-2. barChart.js
import "@/utils/charts/global";
import { Bar } from "~/external/vue-chartjs-3.5.1/src/index";
export default {
extends: Bar,
props: ["chartData", "options"],
watch: {
chartData: {
handler() {
this.renderChart(this.chartData, this.options);
},
deep: true
}
},
mounted() {
this.renderChart(this.chartData, this.options);
}
};
- 저는 vue-chartjs를 외부 파일로 넣어서 사용했습니다.
- vue 파일에서 설정한 데이터와 옵션을 가지고 차트를 그리는 코드입니다.
- watch에 chartData를 넣어서 차트 데이터 변경 시 새로고침 되도록 하였습니다.
- horizontal bar chart도 bar chart와 같이 사용하였습니다.
3-3. HorizontalBarChart.vue
<template>
<div class="bar-box">
<div class="bar">
<bar-chart
ref="barChart"
:chartData="chart.data"
:options="chart.options"
id="chart"
></bar-chart>
</div>
</div>
</template>
import BarChart from "@/utils/charts/barChart.js";
export default {
name: "bar-chart",
components: { BarChart },
data() {
return {
chart: {
data: {
labels: ["하나", "둘", "셋", "넷", "다섯", "여섯"],
datasets: [
{
label: "",
backgroundColor: "pink",
pointBackgroundColor: "white",
borderWidth: 0,
fill: true,
tension: 0.1,
barPercentage: 0.7,
data: [3, 2, 7, 5, 4, 9]
}
]
},
options: {
indexAxis: "y",
plugins: {
legend: {
display: false
},
datalabels: {
display: false
},
tooltip: {
boxWidth: 15
}
},
scales: {
x: {
min: 0,
max: 10,
grid: {
drawBorder: false,
color: "black",
lineWidth: 1
},
ticks: {
callback: (val, index) => {
return val !== 0 ? val : "";
},
padding: 3,
stepSize: 2
}
},
y: {
ticks: {},
grid: {
display: false
}
}
},
responsive: true,
maintainAspectRatio: false,
animation: {
duration: 5000
}
}
}
};
}
- 위 코드의 옵션들에 대한 설명은 2번 링크 하단 내용을 참고해주세요.
- 데이터는 위에서 아래 순서로 보여집니다.
- options에서 indexAxis의 값을 y로 주었기 때문에 가로 막대가 그려지게 됩니다.
4. 결과 화면
이상으로 뷰에서 Chart.js를 사용하여 가로 막대차트를 그려보았습니다.
'Web Developer's Story > VUE.js' 카테고리의 다른 글
[Vue.js] transition-group 양방향 slide navigation 구현 (2) | 2022.10.05 |
---|---|
[Vue.js] vue2-datepicker 일간(day), 주간(week), 월간(month) 사용법 (0) | 2022.09.29 |
[Vue.js] Chart.js Bar Chart 그리기 (0) | 2022.03.15 |
[Vue.js] virtual keyboard - Simple-keyboard 사용법 (1) | 2022.01.05 |
[Vue.js] Chart.js Line Chart 그리기 (0) | 2021.12.28 |