Chart(图表)
基于 Recharts 构建的美观图表,可复制粘贴到应用中。
已更新: chart 组件现在使用 Recharts v3。如果要升级现有图表代码,请参阅更新到 Recharts v3。
来认识一下 Charts。这是一组可复制粘贴到应用中的图表组件。
图表开箱即有美观的样式。它们能与其他组件搭配使用,也可根据项目需求完全自定义。
组件
底层使用 Recharts。
chart 组件围绕组合设计。使用 Recharts 组件构建图表,仅在需要的地方引入 ChartTooltip 等自定义组件。
import { Bar, BarChart } from "recharts"
import { ChartContainer, ChartTooltipContent } from "@/components/ui/chart"
export function MyChart() {
return (
<ChartContainer>
<BarChart data={data}>
<Bar dataKey="value" />
<ChartTooltip content={<ChartTooltipContent />} />
</BarChart>
</ChartContainer>
)
}2
3
4
5
6
7
8
9
10
11
12
13
14
组件直接使用 Recharts,因此你可以自由使用其 API。当 Recharts 发布新版本时,你可以按照官方升级指引更新图表。
这些组件归你所有。
更新到 Recharts v3
如果要将旧版图表代码更新到 Recharts v3:
- 通过 CSS 变量引用图表 token 时,用
var(--chart-1)代替hsl(var(--chart-1))。 - 仅使用
ChartTooltip.defaultIndex设置工具提示的初始状态。在自己的图表状态中保存需持续高亮的图形。 - 当父组件
<BarChart>已定义layout时,从<Bar>移除此属性。 - 为
ChartContainer保留高度、min-h-*或aspect-*,以便ResponsiveContainer在首次渲染时测量尺寸。
安装
npx shadcn@latest add chart1. 安装以下依赖:
npm install recharts2. 将以下代码复制到 components/ui/chart.tsx。
"use client"
import * as React from "react"
import { cn } from "cn"
import * as RechartsPrimitive from "recharts"
import type { TooltipValueType } from "recharts"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
const INITIAL_DIMENSION = { width: 320, height: 200 } as const
type TooltipNameType = number | string
export type ChartConfig = Record<
string,
{
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
>
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />")
}
return context
}
function ChartContainer({
id,
className,
children,
config,
initialDimension = INITIAL_DIMENSION,
...props
}: React.ComponentProps<"div"> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>["children"]
initialDimension?: {
width: number
height: number
}
}) {
const uniqueId = React.useId()
const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`
return (
<ChartContext.Provider value={{ config }}>
<div
data-slot="chart"
data-chart={chartId}
className={cn(
"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer
initialDimension={initialDimension}
>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme ?? config.color
)
if (!colorConfig.length) {
return null
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
.join("\n")}
}
`
)
.join("\n"),
}}
/>
)
}
const ChartTooltip = RechartsPrimitive.Tooltip
function ChartTooltipContent({
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
} & Omit<
RechartsPrimitive.DefaultTooltipContentProps<
TooltipValueType,
TooltipNameType
>,
"accessibilityLayer"
>) {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null
}
const [item] = payload
const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === "string"
? (config[label]?.label ?? label)
: itemConfig?.label
if (labelFormatter) {
return (
<div className={cn("font-medium", labelClassName)}>
{labelFormatter(value, payload)}
</div>
)
}
if (!value) {
return null
}
return <div className={cn("font-medium", labelClassName)}>{value}</div>
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
])
if (!active || !payload?.length) {
return null
}
const nestLabel = payload.length === 1 && indicator !== "dot"
return (
<div
className={cn(
"grid min-w-32 items-start gap-1.5 rounded-lg border border-border/50 bg-popover text-popover-foreground px-2.5 py-1.5 text-xs shadow-xl",
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color ?? item.payload?.fill ?? item.color
return (
<div
key={index}
className={cn(
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
indicator === "dot" && "items-center"
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
{
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}
)}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
"flex flex-1 justify-between",
nestLabel ? "items-end" : "items-center"
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label ?? item.name}
</span>
</div>
{item.value != null && (
<span className="font-mono font-medium text-foreground tabular-nums">
{typeof item.value === "number"
? item.value.toLocaleString()
: String(item.value)}
</span>
)}
</div>
</>
)}
</div>
)
})}
</div>
</div>
)
}
const ChartLegend = RechartsPrimitive.Legend
function ChartLegendContent({
className,
hideIcon = false,
payload,
verticalAlign = "bottom",
nameKey,
}: React.ComponentProps<"div"> & {
hideIcon?: boolean
nameKey?: string
} & RechartsPrimitive.DefaultLegendContentProps) {
const { config } = useChart()
if (!payload?.length) {
return null
}
return (
<div
className={cn(
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className
)}
>
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey ?? item.dataKey ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={index}
className={cn(
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
)
})}
</div>
)
}
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string
) {
if (typeof payload !== "object" || payload === null) {
return undefined
}
const payloadPayload =
"payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined
let configLabelKey: string = key
if (
key in payload &&
typeof payload[key as keyof typeof payload] === "string"
) {
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string
}
return configLabelKey in config ? config[configLabelKey] : config[key]
}
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
ChartStyle,
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
3. 将以下颜色添加到 CSS 文件
@layer base {
:root {
--chart-1: oklch(0.6007 0.1903 257.9419);
--chart-2: oklch(0.6369 0.1247 171.0112);
--chart-3: oklch(0.5495 0.2003 300.1164);
--chart-4: oklch(0.6806 0.1901 45.0513);
--chart-5: oklch(0.6198 0.2297 5.1656);
}
.dark {
--chart-1: oklch(0.6496 0.1885 257.7207);
--chart-2: oklch(0.6943 0.1346 171.9868);
--chart-3: oklch(0.6203 0.1997 300.1454);
--chart-4: oklch(0.7171 0.1878 45.3388);
--chart-5: oklch(0.6604 0.2297 5.1368);
}
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
第一个图表
来构建你的第一个图表。我们将创建柱状图,并添加网格、坐标轴、工具提示和图例。
1. 先定义数据
以下数据表示每月的桌面端和移动端用户数量。
注意: 数据可以采用任意结构。通过 dataKey 属性可将数据映射到图表,下方的数据结构仅供参考。
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 },
]2
3
4
5
6
7
8
2. 定义图表配置
图表配置保存图表的设定。可在其中放置供人阅读的文字(例如标签)、图标及主题使用的颜色 token。
import { type ChartConfig } from "@/components/ui/chart"
const chartConfig = {
desktop: {
label: "Desktop",
color: "var(--chart-1)",
},
mobile: {
label: "Mobile",
color: "var(--chart-2)",
},
} satisfies ChartConfig2
3
4
5
6
7
8
9
10
11
12
3. 构建图表
现在可以使用 Recharts 组件构建图表了。
重要: 请在 ChartContainer 组件上设置 min-h-[VALUE],以便图表能响应尺寸变化。
添加网格
为图表添加网格。
1. 导入 CartesianGrid 组件。
import { Bar, BarChart, CartesianGrid } from "recharts"2. 将 CartesianGrid 组件添加到图表。
<ChartContainer config={chartConfig} className="min-h-[200px] w-full">
<BarChart accessibilityLayer data={chartData}>
<CartesianGrid vertical={false} />
<Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} />
<Bar dataKey="mobile" fill="var(--color-mobile)" radius={4} />
</BarChart>
</ChartContainer>2
3
4
5
6
7
添加坐标轴
我们将用 XAxis 组件为图表添加 x 轴。
1. 导入 XAxis 组件。
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts"2. 将 XAxis 组件添加到图表。
<ChartContainer config={chartConfig} className="h-[200px] w-full">
<BarChart accessibilityLayer data={chartData}>
<CartesianGrid vertical={false} />
<XAxis
dataKey="month"
tickLine={false}
tickMargin={10}
axisLine={false}
tickFormatter={(value) => value.slice(0, 3)}
/>
<Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} />
<Bar dataKey="mobile" fill="var(--color-mobile)" radius={4} />
</BarChart>
</ChartContainer>2
3
4
5
6
7
8
9
10
11
12
13
14
添加工具提示
到目前为止,我们一直在使用 Recharts 自带的组件。chart 组件内置的样式调整,让它们开箱即有美观的样式。
要添加工具提示,我们将使用 chart 提供的自定义 ChartTooltip 和 ChartTooltipContent 组件。
1. 导入 ChartTooltip 和 ChartTooltipContent 组件。
import { ChartTooltip, ChartTooltipContent } from "@/components/ui/chart"2. 将这些组件添加到图表。
<ChartContainer config={chartConfig} className="h-[200px] w-full">
<BarChart accessibilityLayer data={chartData}>
<CartesianGrid vertical={false} />
<XAxis
dataKey="month"
tickLine={false}
tickMargin={10}
axisLine={false}
tickFormatter={(value) => value.slice(0, 3)}
/>
<ChartTooltip content={<ChartTooltipContent />} />
<Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} />
<Bar dataKey="mobile" fill="var(--color-mobile)" radius={4} />
</BarChart>
</ChartContainer>2
3
4
5
6
7
8
9
10
11
12
13
14
15
将光标悬停在图表上即可看到工具提示。很简单吧?两个组件就能做出美观的工具提示。
添加图例
图例也采用同样的做法。我们将使用 chart 中的 ChartLegend 和 ChartLegendContent 组件。
1. 导入 ChartLegend 和 ChartLegendContent 组件。
import { ChartLegend, ChartLegendContent } from "@/components/ui/chart"2. 将这些组件添加到图表。
<ChartContainer config={chartConfig} className="h-[200px] w-full">
<BarChart accessibilityLayer data={chartData}>
<CartesianGrid vertical={false} />
<XAxis
dataKey="month"
tickLine={false}
tickMargin={10}
axisLine={false}
tickFormatter={(value) => value.slice(0, 3)}
/>
<ChartTooltip content={<ChartTooltipContent />} />
<ChartLegend content={<ChartLegendContent />} />
<Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} />
<Bar dataKey="mobile" fill="var(--color-mobile)" radius={4} />
</BarChart>
</ChartContainer>2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
完成了。你已经构建了第一个图表!接下来可以了解什么?
图表配置
在图表配置中定义图表的标签、图标和颜色。
图表配置与图表数据彼此独立。
这样可以在图表之间共享配置和颜色 token。即使数据或颜色 token 保存在远端,或采用不同格式,配置也能独立使用。
import { Monitor } from "lucide-react"
import { type ChartConfig } from "@/components/ui/chart"
const chartConfig = {
desktop: {
label: "Desktop",
icon: Monitor,
// Use color: "var(--chart-1)" for both modes, or specify each mode.
theme: {
light: "var(--chart-1)",
dark: "var(--chart-5)",
},
},
} satisfies ChartConfig2
3
4
5
6
7
8
9
10
11
12
13
14
15
主题
图表内置主题支持。可以使用 CSS 变量(推荐),也可以使用十六进制、hsl 或 oklch 等任意格式的颜色值。
CSS 变量
1. 在 CSS 文件中定义颜色
@layer base {
:root {
--chart-1: oklch(0.6007 0.1903 257.9419);
--chart-2: oklch(0.6369 0.1247 171.0112);
}
.dark {
--chart-1: oklch(0.6496 0.1885 257.7207);
--chart-2: oklch(0.6943 0.1346 171.9868);
}
}2
3
4
5
6
7
8
9
10
11
2. 将颜色添加到 chartConfig
const chartConfig = {
desktop: {
label: "Desktop",
color: "var(--chart-1)",
},
mobile: {
label: "Mobile",
color: "var(--chart-2)",
},
} satisfies ChartConfig2
3
4
5
6
7
8
9
10
直接传入主题色值
需要直接传入色值时,可以使用主题中已有的颜色。
const chartConfig = {
desktop: {
label: "Desktop",
color: "var(--chart-1)",
},
mobile: {
label: "Mobile",
color: "oklch(0.6369 0.1247 171.0112)",
},
tablet: {
label: "Tablet",
color: "oklch(0.5495 0.2003 300.1164)",
},
laptop: {
label: "Laptop",
color: "var(--chart-2)",
},
} satisfies ChartConfig2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
使用颜色
要在图表中使用主题颜色,请通过 var(--color-KEY) 格式引用。
组件
<Bar dataKey="desktop" fill="var(--color-desktop)" />图表数据
const chartData = [
{ browser: "chrome", visitors: 275, fill: "var(--color-chrome)" },
{ browser: "safari", visitors: 200, fill: "var(--color-safari)" },
]2
3
4
Tailwind
<LabelList className="fill-(--color-desktop)" />工具提示
图表工具提示包含标签、名称、指示符和值。可以组合使用这些元素,自定义工具提示。
使用 hideLabel、hideIndicator 属性可以显示或隐藏对应元素,并通过 indicator 属性自定义指示符样式。
使用 labelKey 和 nameKey 为工具提示的标签和名称指定自定义键。
Chart 提供 <ChartTooltip> 和 <ChartTooltipContent> 组件,可使用这两个组件为图表添加自定义工具提示。
import { ChartTooltip, ChartTooltipContent } from "@/components/ui/chart"<ChartTooltip content={<ChartTooltipContent />} />属性
使用以下属性自定义工具提示。
| 属性 | 类型 | 说明 |
|---|---|---|
labelKey | string | 用于标签的配置键或数据键。 |
nameKey | string | 用于名称的配置键或数据键。 |
indicator | dot line 或 dashed | 工具提示的指示符样式。 |
hideLabel | boolean | 是否隐藏标签。 |
hideIndicator | boolean | 是否隐藏指示符。 |
颜色
颜色自动取自图表配置。
自定义
使用 labelKey 和 nameKey 属性为工具提示的标签和名称指定自定义键。
const chartData = [
{ browser: "chrome", visitors: 187, fill: "var(--color-chrome)" },
{ browser: "safari", visitors: 200, fill: "var(--color-safari)" },
]
const chartConfig = {
visitors: {
label: "Total Visitors",
},
chrome: {
label: "Chrome",
color: "var(--chart-1)",
},
safari: {
label: "Safari",
color: "var(--chart-2)",
},
} satisfies ChartConfig2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<ChartTooltip
content={<ChartTooltipContent labelKey="visitors" nameKey="browser" />}
/>2
3
这会将 Total Visitors 用作标签,将 Chrome 和 Safari 用作工具提示的名称。
图例
可以使用自定义的 <ChartLegend> 和 <ChartLegendContent> 组件为图表添加图例。
import { ChartLegend, ChartLegendContent } from "@/components/ui/chart"<ChartLegend content={<ChartLegendContent />} />颜色
颜色自动取自图表配置。
自定义
使用 nameKey 属性为图例名称指定自定义键。
const chartData = [
{ browser: "chrome", visitors: 187, fill: "var(--color-chrome)" },
{ browser: "safari", visitors: 200, fill: "var(--color-safari)" },
]
const chartConfig = {
chrome: {
label: "Chrome",
color: "var(--chart-1)",
},
safari: {
label: "Safari",
color: "var(--chart-2)",
},
} satisfies ChartConfig2
3
4
5
6
7
8
9
10
11
12
13
14
15
<ChartLegend content={<ChartLegendContent nameKey="browser" />} />这会将 Chrome 和 Safari 用作图例名称。
无障碍
可以开启 accessibilityLayer 属性,为图表添加无障碍层。
此属性为图表添加键盘访问和屏幕阅读器支持。
<LineChart accessibilityLayer />RTL
要在 shadcn/ui 中启用 RTL 支持,请参阅 RTL 配置指南。