Vega를 사용하여 CSV 파일에서 데이터를 로드하고, 그래프 설정은 JSON 파일에 정의된 경우에도 쉽게 시각화를 구현할 수 있습니다.
Vega는 외부 데이터를 로드하는 기능을 지원하며, JSON 설정 파일을 함께 사용할 수 있습니다. 아래는 이를 구현하는 방법을 단계별로 설명합니다.
1. SSV 파일 데이터 준비
CSV (컴머로 구분된 값) 파일은 다음과 같이 생겼다고 가정합니다.
data.ssv:
category,amount
A,28
B,55
C,43
D,91
E,81
F,53
G,19
H,87
2. JSON 설정 파일 준비
차트 설정은 JSON 파일로 저장합니다. 예를 들어, chart_config.json:
{
"$schema": "https://vega.github.io/schema/vega/v5.json",
"width": 400,
"height": 200,
"padding": 5,
"data": [
{
"name": "table",
"url": "data.csv",
"format": {
"type": "csv",
"delimiter": ","
}
}
],
"marks": [
{
"type": "rect",
"from": {"data": "table"},
"encode": {
"enter": {
"x": {"scale": "xscale", "field": "category"},
"width": {"scale": "xscale", "band": 1},
"y": {"scale": "yscale", "field": "amount"},
"y2": {"scale": "yscale", "value": 0}
},
"update": {
"fill": {"value": "steelblue"}
},
"hover": {
"fill": {"value": "red"}
}
}
}
],
"scales": [
{
"name": "xscale",
"type": "band",
"domain": {"data": "table", "field": "category"},
"range": "width"
},
{
"name": "yscale",
"domain": {"data": "table", "field": "amount"},
"nice": true,
"range": "height"
}
],
"axes": [
{"orient": "bottom", "scale": "xscale"},
{"orient": "left", "scale": "yscale"}
]
}
3. HTML 파일 작성
HTML에서 JSON 설정과 데이터를 함께 로드합니다.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>
</head>
<body>
<div id="chart"></div>
<script>
// JSON 파일 경로
const jsonUrl = "chart_config.json";
// Vega Embed로 JSON 파일 렌더링
vegaEmbed("#chart", jsonUrl).catch(console.error);
</script>
</body>
</html>
4. 파일 구조
다음과 같은 디렉토리 구조로 파일을 배치해야 합니다:
project-folder/
│
├── index.html # HTML 파일
├── chart_config.json # Vega 설정 파일
├── data.csv # SSV 데이터 파일
5. 결과
위 코드를 실행하면 SSV 파일의 데이터를 읽어서 JSON 설정에 따라 차트를 렌더링합니다.
6. 유용한 팁
1. 다른 데이터 포맷: type을 "json", "tsv", "ssv"로 변경하면 해당 포맷에 맞는 데이터를 로드할 수 있습니다.
2. Vega Editor 사용: Vega Editor에서 설정 파일을 실시간으로 수정하고 결과를 확인할 수 있습니다.
3. 데이터 경로 문제 해결:
• 데이터 파일과 JSON 파일이 같은 폴더에 있어야 합니다.
• 또는 절대 경로를 사용해 파일 위치를 명확히 지정하세요.