图表
使用 recharts 和 Chakra UI 创建精美图表
图表设计精美,开箱即用,可与其他 Chakra UI 主题系统无缝集成。图表基于 recharts 构建
¥Charts are designed to look great out of the box, seamlessly integrating with other Chakra UI's theming system. The charts are built on top of recharts
安装
¥Installation
运行以下命令以安装图表及其对等依赖。
¥Run the following command to install the charts and its peer dependencies.
npm i @chakra-ui/charts recharts
用法
¥Usage
导入图表组件
¥Import the charts component
在大多数情况下,你需要从 @chakra-ui/charts 包中导入 Chart 和 useChart 钩子,然后将它们与 recharts 组件组合使用。
¥In most cases, you need to import the Chart and useChart hook from the
@chakra-ui/charts package, then combine them with the components recharts
import { Chart, useChart } from "@chakra-ui/charts"
import { Bar, BarChart, XAxis, YAxis } from "recharts"渲染图表
¥Render the chart
根据你从 recharts 库中需要的图表类型,将图表组件封装在 Chart.Root 组件中。
¥Depending on the chart type you need from the recharts library, wrap the chart
component within the Chart.Root component.
<Chart.Root chart={chart}>
<BarChart data={chart.data}>
{chart.series.map((item) => (
<Bar
key={item.name}
dataKey={chart.key(item.name)}
fill={chart.color(item.color)}
/>
))}
</BarChart>
</Chart.Root>自定义
¥Customization
图表组件基于 Recharts 构建,因此你可以使用 Recharts 提供的所有自定义选项。
¥The charts component is built on top of Recharts, so you can use all the customization options that Recharts provides.
颜色
¥Colors
useChart 钩子提供了 color 函数,可从 recharts 查询图表组件的语义颜色。
¥The useChart hook provides a color function that you can use to query
semantic colors for the chart component from recharts.
<CartesianGrid stroke={chart.color("border.muted")} />
格式化程序
¥Formatters
useChart 钩子提供了 formatDate 和 formatNumber 函数,可分别用于格式化日期和数字。这对于格式化 x、y 轴标签和工具提示非常有用。
¥The useChart hook provides a formatDate and formatNumber function that you
can use to format the date and number respectively. This is useful for
formatting the x, y axis labels and tooltips.
// format the x-axis labels
<XAxis tickFormatter={chart.formatDate({ month: "short", day: "2-digit" })} />
// format the y-axis labels
<YAxis tickFormatter={chart.formatNumber({ maximumFractionDigits: 1 })} />