Chart
복사해서 붙여넣는 방식으로 바로 쓸 수 있는 차트 컴포넌트 모음이에요. LayerChart를 기반으로 만들어졌고, 앱에 가져다 넣은 뒤 프로젝트에 맞게 자유롭게 고칠 수 있어요.
출처: 문서
본문
Charts를 소개해요. 앱에 복사해서 붙여넣을 수 있는 차트 컴포넌트 모음이에요.
Charts는 기본 상태에서도 보기 좋게 디자인됐어요. 다른 컴포넌트와 잘 어울리고, 프로젝트에 맞게 완전히 커스터마이징할 수 있어요.
컴포넌트(Component)
내부적으로는 LayerChart를 사용해요.
Chart 컴포넌트는 조합(composition)을 전제로 설계됐어요. 차트는 LayerChart 컴포넌트들로 만들고, ChartTooltip 같은 커스텀 컴포넌트는 필요한 시점에 필요한 곳에만 가져다 쓰면 돼요
<script lang="ts">
import * as Chart from "$lib/components/ui/chart/index.js";
import { BarChart } from "layerchart";
const data = [
// ...
];
</script>
<Chart.Container>
<BarChart {data} x="date" y="value">
{#snippet tooltip()}
<Chart.Tooltip />
{/snippet}
</BarChart>
</Chart.Container>
LayerChart를 감싸서 추상화하지 않아요. 그래서 특정 추상화에 갇히지 않아요. LayerChart의 새 버전이 나오면 공식 업그레이드 경로를 따라 차트를 업그레이드하면 돼요.
컴포넌트는 여러분의 소유예요.
설치(Installation)
pnpm dlx shadcn-svelte@latest add chart
npx shadcn-svelte@latest add chart
bun x shadcn-svelte@latest add chart
첫 번째 차트 만들기(Your First Chart)
첫 번째 차트를 만들어 봐요. 축과 그리드, 툴팁, 범례가 있는 막대 차트를 만들 거예요.
데이터부터 정의하기(Start by defining your data)
다음 데이터는 매월 데스크톱 사용자 수와 모바일 사용자 수를 나타내요.
참고: 데이터는 어떤 형태든 상관없어요. 아래 데이터의 모양에 한정되지 않아요. dataKey prop으로 여러분의 데이터를 차트에 매핑해요.
lib/components/example-chart.svelte
<script lang="ts">
const chartData = [
{ month: "January", desktop: 186, mobile: 80 },
{ month: "February", desktop: 305, mobile: 200 },
{ month: "March", desktop: 237, mobile: 120 },
{ month: "April", desktop: 73, mobile: 190 },
{ month: "May", desktop: 209, mobile: 130 },
{ month: "June", desktop: 214, mobile: 140 },
];
</script>
차트 config 정의하기(Define your chart config)
차트 config는 차트의 설정을 담는 곳이에요. 레이블, 아이콘 같은 사람이 읽을 수 있는 문자열과 테마용 컬러 토큰을 여기에 둬요.
lib/components/example-chart.svelte
<script lang="ts">
import * as Chart from "$lib/components/ui/chart/index.js";
const chartConfig = {
desktop: {
label: "Desktop",
color: "#2563eb",
},
mobile: {
label: "Mobile",
color: "#60a5fa",
},
} satisfies Chart.ChartConfig;
</script>
차트 만들기(Build your chart)
이제 LayerChart 컴포넌트로 차트를 만들면 돼요. 이 예제에서는 LayerChart의 "Simplified Charts" 중 하나인 BarChart 컴포넌트를 사용해요.
이런 컴포넌트들은 차트에서 흔히 필요한 스캐폴딩을 대신 처리해 주면서, 원하는 대로 커스터마이징할 수 있는 여지도 남겨줘요.
<script lang="ts">
import { scaleBand } from "d3-scale";
import { BarChart } from "layerchart";
import * as Chart from "$lib/components/ui/chart/index.js";
const chartData = [
{ month: "January", desktop: 186, mobile: 80 },
{ month: "February", desktop: 305, mobile: 200 },
{ month: "March", desktop: 237, mobile: 120 },
{ month: "April", desktop: 73, mobile: 190 },
{ month: "May", desktop: 209, mobile: 130 },
{ month: "June", desktop: 214, mobile: 140 }
];
const chartConfig = {
desktop: {
label: "Desktop",
color: "#2563eb"
},
mobile: {
label: "Mobile",
color: "#60a5fa"
}
} satisfies Chart.ChartConfig;
</script>
<Chart.Container config={chartConfig} class="min-h-[200px] w-full">
<BarChart
data={chartData}
xScale={scaleBand().padding(0.25)}
x="month"
axis="x"
seriesLayout="group"
tooltipContext={false}
series={[
{
key: "desktop",
label: chartConfig.desktop.label,
color: chartConfig.desktop.color
},
{
key: "mobile",
label: chartConfig.mobile.label,
color: chartConfig.mobile.color
}
]}
/>
</Chart.Container>
View Code
이제 x축과 그리드가 있는 그룹 막대 차트가 완성됐어요.
축 눈금 조정하기(Adjusting the Axis Ticks)
지금 막대 차트는 x축의 눈금마다 월 이름 전체를 보여주고 있어요. 앞 세 글자만 보이도록 줄여 봐요.
x축에 커스텀 포매터 추가하기(Add a custom formatter to the x axis)
props prop은 차트를 구성하는 여러 컴포넌트에 커스텀 prop을 전달할 때 써요. 여기서는 x축에 커스텀 포매터를 전달하고 있어요.
<Chart.Container config={chartConfig} class="min-h-[200px] w-full">
<BarChart
data={chartData}
xScale={scaleBand().padding(0.25)}
x="month"
axis="x"
tooltipContext={false}
seriesLayout="group"
series={[
{
key: "desktop",
label: chartConfig.desktop.label,
color: chartConfig.desktop.color,
},
{
key: "mobile",
label: chartConfig.mobile.label,
color: chartConfig.mobile.color,
},
]}
props={{
xAxis: {
format: (d) => d.slice(0, 3),
},
}}
/>
</Chart.Container>
<script lang="ts">
import { scaleBand } from "d3-scale";
import { BarChart } from "layerchart";
import * as Chart from "$lib/components/ui/chart/index.js";
const chartData = [
{ month: "January", desktop: 186, mobile: 80 },
{ month: "February", desktop: 305, mobile: 200 },
{ month: "March", desktop: 237, mobile: 120 },
{ month: "April", desktop: 73, mobile: 190 },
{ month: "May", desktop: 209, mobile: 130 },
{ month: "June", desktop: 214, mobile: 140 }
];
const chartConfig = {
desktop: {
label: "Desktop",
color: "#2563eb"
},
mobile: {
label: "Mobile",
color: "#60a5fa"
}
} satisfies Chart.ChartConfig;
</script>
<Chart.Container config={chartConfig} class="min-h-[200px] w-full">
<BarChart
data={chartData}
xScale={scaleBand().padding(0.25)}
x="month"
axis="x"
seriesLayout="group"
series={[
{
key: "desktop",
label: chartConfig.desktop.label,
color: chartConfig.desktop.color
},
{
key: "mobile",
label: chartConfig.mobile.label,
color: chartConfig.mobile.color
}
]}
props={{
xAxis: {
format: (d) => d.slice(0, 3)
}
}}
/>
</Chart.Container>
View Code
툴팁 추가하기(Add Tooltip)
지금까지는 LayerChart의 BarChart 컴포넌트만 사용했어요. chart 컴포넌트 쪽에서 몇 가지 커스터마이징을 해 뒀기 때문에 기본 상태에서도 잘 어울려요.
툴팁을 추가하려면 chart가 제공하는 커스텀 Chart.Tooltip 컴포넌트를 사용해요.
차트에 Chart.Tooltip 컴포넌트 추가하기(Add the Chart.Tooltip component to the chart)
tooltipContext={false} prop을 tooltip 스니펫으로 바꾸고, 그 안에 Chart.Tooltip 컴포넌트를 넣을 거예요.
<Chart.Container config={chartConfig} class="min-h-[200px] w-full">
<BarChart
data={chartData}
xScale={scaleBand().padding(0.25)}
x="month"
axis="x"
seriesLayout="group"
series={[
{
key: "desktop",
label: chartConfig.desktop.label,
color: chartConfig.desktop.color,
},
{
key: "mobile",
label: chartConfig.mobile.label,
color: chartConfig.mobile.color,
},
]}
props={{
xAxis: {
format: (d) => d.slice(0, 3),
},
}}
>
{#snippet tooltip()}
<Chart.Tooltip />
{/snippet}
</BarChart>
</Chart.Container>
<script lang="ts">
import { scaleBand } from "d3-scale";
import { BarChart } from "layerchart";
import * as Chart from "$lib/components/ui/chart/index.js";
const chartData = [
{ month: "January", desktop: 186, mobile: 80 },
{ month: "February", desktop: 305, mobile: 200 },
{ month: "March", desktop: 237, mobile: 120 },
{ month: "April", desktop: 73, mobile: 190 },
{ month: "May", desktop: 209, mobile: 130 },
{ month: "June", desktop: 214, mobile: 140 }
];
const chartConfig = {
desktop: {
label: "Desktop",
color: "#2563eb"
},
mobile: {
label: "Mobile",
color: "#60a5fa"
}
} satisfies Chart.ChartConfig;
</script>
<Chart.Container config={chartConfig} class="min-h-[200px] w-full">
<BarChart
data={chartData}
xScale={scaleBand().padding(0.25)}
x="month"
axis="x"
seriesLayout="group"
series={[
{
key: "desktop",
label: chartConfig.desktop.label,
color: chartConfig.desktop.color
},
{
key: "mobile",
label: chartConfig.mobile.label,
color: chartConfig.mobile.color
}
]}
>
{#snippet tooltip()}
<Chart.Tooltip />
{/snippet}
</BarChart>
</Chart.Container>
View Code
범례 추가하기(Add Legend)
legend prop을 true로 설정하기(Set the legend prop to true)
legend prop은 차트에 범례를 보여줄 때 사용해요. 커스텀 범례를 더 쉽게 만들 수 있도록, 툴팁과 비슷한 payload를 추가할 수 있게 LayerChart 쪽과 협력해 작업 중이에요.
<Chart.Container config={chartConfig} class="min-h-[200px] w-full">
<BarChart
data={chartData}
xScale={scaleBand().padding(0.25)}
x="month"
axis="x"
seriesLayout="group"
legend
series={[
{
key: "desktop",
label: chartConfig.desktop.label,
color: chartConfig.desktop.color,
},
{
key: "mobile",
label: chartConfig.mobile.label,
color: chartConfig.mobile.color,
},
]}
props={{
xAxis: {
format: (d) => d.slice(0, 3),
},
}}
>
{#snippet tooltip()}
<Chart.Tooltip />
{/snippet}
</BarChart>
</Chart.Container>
<script lang="ts">
import { scaleBand } from "d3-scale";
import { BarChart } from "layerchart";
import * as Chart from "$lib/components/ui/chart/index.js";
const chartData = [
{ month: "January", desktop: 186, mobile: 80 },
{ month: "February", desktop: 305, mobile: 200 },
{ month: "March", desktop: 237, mobile: 120 },
{ month: "April", desktop: 73, mobile: 190 },
{ month: "May", desktop: 209, mobile: 130 },
{ month: "June", desktop: 214, mobile: 140 }
];
const chartConfig = {
desktop: {
label: "Desktop",
color: "#2563eb"
},
mobile: {
label: "Mobile",
color: "#60a5fa"
}
} satisfies Chart.ChartConfig;
</script>
<Chart.Container config={chartConfig} class="min-h-[200px] w-full">
<BarChart
data={chartData}
xScale={scaleBand().padding(0.25)}
x="month"
axis="x"
seriesLayout="group"
legend
series={[
{
key: "desktop",
label: chartConfig.desktop.label,
color: chartConfig.desktop.color
},
{
key: "mobile",
label: chartConfig.mobile.label,
color: chartConfig.mobile.color
}
]}
>
{#snippet tooltip()}
<Chart.Tooltip />
{/snippet}
</BarChart>
</Chart.Container>
View Code
완료됐어요. 첫 번째 차트를 만들었어요! 다음은 뭘 할까요?
- Themes and Colors
- Tooltip ## Chart Config
차트 config에서는 차트의 레이블, 아이콘, 색상을 정의해요.
차트 데이터와는 의도적으로 분리되어 있어요.
이 덕분에 여러 차트 사이에서 config와 컬러 토큰을 공유할 수 있어요. 데이터나 컬러 토큰이 원격에 있거나 다른 형식으로 되어 있는 경우에도 독립적으로 동작할 수 있어요.
<script lang="ts">
import MonitorIcon from "@lucide/svelte/icons/monitor";
import * as Chart from "$lib/components/ui/chart/index.js";
const chartConfig = {
desktop: {
label: "Desktop",
icon: MonitorIcon,
// A color like 'hsl(220, 98%, 61%)' or 'var(--color-name)'
color: "#2563eb",
// OR a theme object with 'light' and 'dark' keys
theme: {
light: "#2563eb",
dark: "#dc2626",
},
},
} satisfies Chart.ChartConfig;
</script>
테마(Theming)
Charts는 테마 기능을 기본으로 지원해요. CSS 변수(권장)를 쓰거나, hex·hsl·oklch 같은 어떤 형식의 색상 값이든 사용할 수 있어요.
CSS 변수(CSS Variables)
CSS 파일에 색상 정의하기(Define your colors in your css file)
src/routes/layout.css
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
/* ... */
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
/* ... */
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
}
chartConfig에 색상 추가하기(Add the color to your chartConfig)
<script lang="ts">
const chartConfig = {
desktop: {
label: "Desktop",
color: "var(--chart-1)",
},
mobile: {
label: "Mobile",
color: "var(--chart-2)",
},
} satisfies Chart.ChartConfig;
</script>
hex, hsl or oklch
차트 config에 색상을 직접 정의할 수도 있어요. 선호하는 색상 형식을 그대로 쓰면 돼요.
<script lang="ts">
const chartConfig = {
desktop: {
label: "Desktop",
color: "#2563eb",
},
} satisfies Chart.ChartConfig;
</script>
색상 사용하기(Using Colors)
차트에서 테마 색상을 사용하려면 var(--color-KEY) 형식으로 색상을 참조해요.
컴포넌트(Components)
<Bar fill="var(--color-desktop)" />
차트 데이터(Chart Data)
const chartData = [
{ browser: "chrome", visitors: 275, color: "var(--color-chrome)" },
{ browser: "safari", visitors: 200, color: "var(--color-safari)" },];
Tailwind
<Label class="fill-(--color-desktop)" />
툴팁(Tooltip)
차트 툴팁은 레이블, 이름, 인디케이터, 값으로 구성돼요. 이 요소들을 조합해서 툴팁을 원하는 모양으로 커스터마이징할 수 있어요.
hideLabel, hideIndicator props로 각 요소를 켜고 끌 수 있고, indicator prop으로 인디케이터 스타일을 바꿀 수 있어요.
툴팁의 레이블과 이름에 커스텀 키를 쓰려면 labelKey와 nameKey를 사용해요.
Chart에는 <Chart.Tooltip> 컴포넌트가 포함되어 있어요. 이 컴포넌트로 차트에 커스텀 툴팁을 추가할 수 있어요.
Props
아래 props로 툴팁을 커스터마이징해요.
| Prop | Type | Description |
|---|---|---|
labelKey |
string | The config or data key to use for the label. |
nameKey |
string | The config or data key to use for the name. |
indicator |
dot line or dashed |
The indicator style for the tooltip. |
hideLabel |
boolean | Whether to hide the label. |
hideIndicator |
boolean | Whether to hide the indicator. |
label |
string | A custom label for the tooltip |
labelFormatter |
function | A function to format the label. |
formatter |
Snippet | A snippet to provide flexible rendering of the tooltip. |
색상(Colors)
색상은 차트 config에서 자동으로 참조해요.
커스텀(Custom)
툴팁의 레이블과 이름에 커스텀 키를 사용하려면 labelKey와 nameKey props를 쓰면 돼요.
<script lang="ts">
const chartData = [
{ browser: "chrome", visitors: 187, color: "var(--color-chrome)" },
{ browser: "safari", visitors: 200, color: "var(--color-safari)" },
];
const chartConfig = {
visitors: {
label: "Total Visitors",
},
chrome: {
label: "Chrome",
color: "var(--chart-1)",
},
safari: {
label: "Safari",
color: "var(--chart-2)",
},
} satisfies ChartConfig;
</script>
<Chart.Tooltip labelKey="visitors" nameKey="browser" />
이렇게 하면 레이블에는 Total Visitors가, 툴팁 이름에는 Chrome과 Safari가 사용돼요.
더 알아보기 (Learn more)
더 많은 차트 종류와 테마 예시는 shadcn-svelte 공식 문서의 Chart 페이지와 Charts 라이브러리에서 확인할 수 있어요. LayerChart의 컴포넌트 레퍼런스도 함께 보면 커스터마이징 폭이 넓어져요.