recharts

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Recharts

Recharts

React charting library built on top of D3 for composable, declarative data visualization.
基于D3构建的React图表库,支持可组合、声明式的数据可视化。

Quick Start

快速开始

1. Install Recharts

1. 安装Recharts

bash
npm install recharts
bash
npm install recharts

2. Basic Chart Structure

2. 基础图表结构

All Recharts charts follow the same pattern:
jsx
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';

const data = [
  { name: 'Jan', sales: 4000, profit: 2400 },
  { name: 'Feb', sales: 3000, profit: 1398 },
  { name: 'Mar', sales: 2000, profit: 9800 },
];

<ResponsiveContainer width="100%" height={300}>
  <LineChart data={data}>
    <CartesianGrid strokeDasharray="3 3" />
    <XAxis dataKey="name" />
    <YAxis />
    <Tooltip />
    <Legend />
    <Line type="monotone" dataKey="sales" stroke="#8884d8" />
    <Line type="monotone" dataKey="profit" stroke="#82ca9d" />
  </LineChart>
</ResponsiveContainer>
所有Recharts图表都遵循相同的结构:
jsx
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';

const data = [
  { name: 'Jan', sales: 4000, profit: 2400 },
  { name: 'Feb', sales: 3000, profit: 1398 },
  { name: 'Mar', sales: 2000, profit: 9800 },
];

<ResponsiveContainer width="100%" height={300}>
  <LineChart data={data}>
    <CartesianGrid strokeDasharray="3 3" />
    <XAxis dataKey="name" />
    <YAxis />
    <Tooltip />
    <Legend />
    <Line type="monotone" dataKey="sales" stroke="#8884d8" />
    <Line type="monotone" dataKey="profit" stroke="#82ca9d" />
  </LineChart>
</ResponsiveContainer>

Core Concepts

核心概念

Data Format

数据格式

Recharts expects data as an array of objects. Each object represents a data point:
javascript
const data = [
  { month: 'Jan', revenue: 4000, expenses: 2400 },
  { month: 'Feb', revenue: 3000, expenses: 1398 },
];
Use
dataKey
props to map object properties to chart components:
  • dataKey="revenue"
    - maps to the revenue property
  • dataKey={(entry) => entry.revenue - entry.expenses}
    - function for computed values
Recharts要求数据为对象数组,每个对象代表一个数据点:
javascript
const data = [
  { month: 'Jan', revenue: 4000, expenses: 2400 },
  { month: 'Feb', revenue: 3000, expenses: 1398 },
];
使用
dataKey
属性将对象属性映射到图表组件:
  • dataKey="revenue"
    - 映射到revenue属性
  • dataKey={(entry) => entry.revenue - entry.expenses}
    - 用于计算值的函数

Component Composition

组件组合

Charts are built by nesting specialized components:
Sizing: Use the
responsive
prop (v3.3+),
ResponsiveContainer
wrapper, or set
width
/
height
directly
Chart types (choose one):
  • LineChart
    - Line and area visualizations
  • BarChart
    - Bar and column charts
  • AreaChart
    - Stacked and filled area charts
  • PieChart
    - Pie and donut charts
  • ScatterChart
    - Scatter plots and bubble charts
  • ComposedChart
    - Mixed chart types
  • RadarChart
    - Radar/spider charts
  • RadialBarChart
    - Circular bar charts
Common child components:
  • XAxis
    /
    YAxis
    - Axis configuration
  • CartesianGrid
    - Grid lines
  • Tooltip
    - Hover information
  • Legend
    - Series identification
  • Line
    /
    Bar
    /
    Area
    /
    Pie
    - Data series visualization
通过嵌套专用组件来构建图表:
尺寸设置:使用
responsive
属性(v3.3+)、
ResponsiveContainer
包装器,或直接设置
width
/
height
图表类型(选择其一):
  • LineChart
    - 折线和面积可视化
  • BarChart
    - 柱状和条形图
  • AreaChart
    - 堆叠和填充面积图
  • PieChart
    - 饼图和环形图
  • ScatterChart
    - 散点图和气泡图
  • ComposedChart
    - 混合图表类型
  • RadarChart
    - 雷达图/蜘蛛图
  • RadialBarChart
    - 环形柱状图
通用子组件:
  • XAxis
    /
    YAxis
    - 坐标轴配置
  • CartesianGrid
    - 网格线
  • Tooltip
    - 悬停信息
  • Legend
    - 系列标识
  • Line
    /
    Bar
    /
    Area
    /
    Pie
    - 数据系列可视化

Chart Patterns by Type

按类型划分的图表模式

Line Charts

折线图

jsx
<LineChart data={data}>
  <XAxis dataKey="name" />
  <YAxis />
  <CartesianGrid strokeDasharray="3 3" />
  <Tooltip />
  <Legend />
  <Line type="monotone" dataKey="value" stroke="#8884d8" strokeWidth={2} dot={{ r: 4 }} />
</LineChart>
Key props:
  • type
    : "monotone" (smooth), "linear", "step", "natural"
  • stroke
    : line color
  • strokeWidth
    : line thickness
  • dot
    : point styling (set to
    false
    to hide)
  • activeDot
    : hovered point styling
  • connectNulls
    : true to connect gaps
jsx
<LineChart data={data}>
  <XAxis dataKey="name" />
  <YAxis />
  <CartesianGrid strokeDasharray="3 3" />
  <Tooltip />
  <Legend />
  <Line type="monotone" dataKey="value" stroke="#8884d8" strokeWidth={2} dot={{ r: 4 }} />
</LineChart>
关键属性:
  • type
    : "monotone"(平滑)、"linear"(线性)、"step"(阶梯)、"natural"(自然)
  • stroke
    : 线条颜色
  • strokeWidth
    : 线条粗细
  • dot
    : 点样式(设置为
    false
    可隐藏)
  • activeDot
    : 悬停点样式
  • connectNulls
    : 设置为true可连接数据间隙

Area Charts

面积图

jsx
<AreaChart data={data}>
  <defs>
    <linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
      <stop offset="5%" stopColor="#8884d8" stopOpacity={0.8}/>
      <stop offset="95%" stopColor="#8884d8" stopOpacity={0}/>
    </linearGradient>
  </defs>
  <XAxis dataKey="name" />
  <YAxis />
  <CartesianGrid strokeDasharray="3 3" />
  <Tooltip />
  <Area type="monotone" dataKey="value" stroke="#8884d8" fillOpacity={1} fill="url(#colorValue)" />
</AreaChart>
Stacked areas:
jsx
<Area type="monotone" dataKey="sales" stackId="1" stroke="#8884d8" fill="#8884d8" />
<Area type="monotone" dataKey="profit" stackId="1" stroke="#82ca9d" fill="#82ca9d" />
jsx
<AreaChart data={data}>
  <defs>
    <linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
      <stop offset="5%" stopColor="#8884d8" stopOpacity={0.8}/>
      <stop offset="95%" stopColor="#8884d8" stopOpacity={0}/>
    </linearGradient>
  </defs>
  <XAxis dataKey="name" />
  <YAxis />
  <CartesianGrid strokeDasharray="3 3" />
  <Tooltip />
  <Area type="monotone" dataKey="value" stroke="#8884d8" fillOpacity={1} fill="url(#colorValue)" />
</AreaChart>
堆叠面积图:
jsx
<Area type="monotone" dataKey="sales" stackId="1" stroke="#8884d8" fill="#8884d8" />
<Area type="monotone" dataKey="profit" stackId="1" stroke="#82ca9d" fill="#82ca9d" />

Bar Charts

柱状图

jsx
<BarChart data={data}>
  <XAxis dataKey="name" />
  <YAxis />
  <CartesianGrid strokeDasharray="3 3" />
  <Tooltip />
  <Legend />
  <Bar dataKey="sales" fill="#8884d8" radius={[4, 4, 0, 0]} />
  <Bar dataKey="profit" fill="#82ca9d" radius={[4, 4, 0, 0]} />
</BarChart>
Key props:
  • fill
    : bar color
  • radius
    : rounded corners [topLeft, topRight, bottomRight, bottomLeft] or single number for all corners
  • barSize
    : fixed bar width
  • stackId
    : group bars into stacks
  • shape
    : custom bar shape (function or element)
Stacked bars:
jsx
<Bar dataKey="sales" stackId="a" fill="#8884d8" />
<Bar dataKey="profit" stackId="a" fill="#82ca9d" />
Rounded stacked bars (use
BarStack
to round the whole stack):
jsx
import { BarStack } from 'recharts';

<BarChart data={data}>
  <BarStack stackId="a" radius={[4, 4, 0, 0]}>
    <Bar dataKey="sales" fill="#8884d8" />
    <Bar dataKey="profit" fill="#82ca9d" />
  </BarStack>
</BarChart>
jsx
<BarChart data={data}>
  <XAxis dataKey="name" />
  <YAxis />
  <CartesianGrid strokeDasharray="3 3" />
  <Tooltip />
  <Legend />
  <Bar dataKey="sales" fill="#8884d8" radius={[4, 4, 0, 0]} />
  <Bar dataKey="profit" fill="#82ca9d" radius={[4, 4, 0, 0]} />
</BarChart>
关键属性:
  • fill
    : 柱状图颜色
  • radius
    : 圆角设置 [左上, 右上, 右下, 左下] 或单个数值设置所有圆角
  • barSize
    : 固定柱状图宽度
  • stackId
    : 将柱状图分组为堆叠
  • shape
    : 自定义柱状图形状(函数或元素)
堆叠柱状图:
jsx
<Bar dataKey="sales" stackId="a" fill="#8884d8" />
<Bar dataKey="profit" stackId="a" fill="#82ca9d" />
圆角堆叠柱状图(使用
BarStack
为整个堆叠设置圆角):
jsx
import { BarStack } from 'recharts';

<BarChart data={data}>
  <BarStack stackId="a" radius={[4, 4, 0, 0]}>
    <Bar dataKey="sales" fill="#8884d8" />
    <Bar dataKey="profit" fill="#82ca9d" />
  </BarStack>
</BarChart>

Pie Charts

饼图

jsx
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

<PieChart>
  <Pie
    data={data}
    dataKey="value"
    nameKey="name"
    cx="50%"
    cy="50%"
    innerRadius={60}
    outerRadius={80}
    paddingAngle={5}
    shape={(props) => <Sector {...props} fill={COLORS[props.index % COLORS.length]} />}
  />
  <Tooltip />
  <Legend />
</PieChart>
Key props:
  • innerRadius
    : creates donut chart when > 0
  • outerRadius
    : pie size
  • paddingAngle
    : gap between slices
  • startAngle
    /
    endAngle
    : partial pie (default: 0 to 360)
  • label
    : shows values on slices
  • shape
    : custom render for each slice (replaces deprecated
    Cell
    component)
jsx
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

<PieChart>
  <Pie
    data={data}
    dataKey="value"
    nameKey="name"
    cx="50%"
    cy="50%"
    innerRadius={60}
    outerRadius={80}
    paddingAngle={5}
    shape={(props) => <Sector {...props} fill={COLORS[props.index % COLORS.length]} />}
  />
  <Tooltip />
  <Legend />
</PieChart>
关键属性:
  • innerRadius
    : 大于0时创建环形图
  • outerRadius
    : 饼图大小
  • paddingAngle
    : 扇区间隙
  • startAngle
    /
    endAngle
    : 部分饼图(默认:0到360)
  • label
    : 在扇区上显示数值
  • shape
    : 自定义每个扇区的渲染(替代已弃用的
    Cell
    组件)

Scatter Charts

散点图

jsx
<ScatterChart>
  <XAxis type="number" dataKey="x" name="X Axis" />
  <YAxis type="number" dataKey="y" name="Y Axis" />
  <CartesianGrid />
  <Tooltip cursor={{ strokeDasharray: '3 3' }} />
  <Scatter name="Series A" data={data} fill="#8884d8" />
</ScatterChart>
jsx
<ScatterChart>
  <XAxis type="number" dataKey="x" name="X Axis" />
  <YAxis type="number" dataKey="y" name="Y Axis" />
  <CartesianGrid />
  <Tooltip cursor={{ strokeDasharray: '3 3' }} />
  <Scatter name="Series A" data={data} fill="#8884d8" />
</ScatterChart>

Composed Charts

组合图

Mix multiple chart types:
jsx
<ComposedChart data={data}>
  <XAxis dataKey="name" />
  <YAxis />
  <CartesianGrid stroke="#f5f5f5" />
  <Tooltip />
  <Legend />
  <Area type="monotone" dataKey="total" fill="#8884d8" stroke="#8884d8" />
  <Bar dataKey="sales" barSize={20} fill="#413ea0" />
  <Line type="monotone" dataKey="profit" stroke="#ff7300" />
</ComposedChart>
混合多种图表类型:
jsx
<ComposedChart data={data}>
  <XAxis dataKey="name" />
  <YAxis />
  <CartesianGrid stroke="#f5f5f5" />
  <Tooltip />
  <Legend />
  <Area type="monotone" dataKey="total" fill="#8884d8" stroke="#8884d8" />
  <Bar dataKey="sales" barSize={20} fill="#413ea0" />
  <Line type="monotone" dataKey="profit" stroke="#ff7300" />
</ComposedChart>

Responsive Sizing

响应式尺寸设置

Option 1:
responsive
prop (Recharts 3.3+, recommended)

选项1:
responsive
属性(Recharts 3.3+,推荐)

Set
responsive
on the chart itself. Uses standard CSS sizing rules:
jsx
<LineChart data={data} width="100%" height={300} responsive>
  {/* chart components */}
</LineChart>
Works with flexbox and CSS grid layouts. Also supports CSS
style
props:
jsx
<LineChart data={data} responsive style={{ maxWidth: 800, width: '100%', aspectRatio: '16/9' }}>
  {/* chart components */}
</LineChart>
在图表本身设置
responsive
,使用标准CSS尺寸规则:
jsx
<LineChart data={data} width="100%" height={300} responsive>
  {/* 图表组件 */}
</LineChart>
适用于flexbox和CSS网格布局,也支持CSS
style
属性:
jsx
<LineChart data={data} responsive style={{ maxWidth: 800, width: '100%', aspectRatio: '16/9' }}>
  {/* 图表组件 */}
</LineChart>

Option 2:
ResponsiveContainer
(older versions)

选项2:
ResponsiveContainer
(旧版本)

For Recharts < 3.3, wrap chart in
ResponsiveContainer
:
jsx
<ResponsiveContainer width="100%" height={300}>
  <LineChart data={data}>
    {/* chart components */}
  </LineChart>
</ResponsiveContainer>
Critical:
ResponsiveContainer
must have a parent with defined dimensions. Height must be a number, not a percentage.
对于Recharts < 3.3,使用
ResponsiveContainer
包装图表:
jsx
<ResponsiveContainer width="100%" height={300}>
  <LineChart data={data}>
    {/* 图表组件 */}
  </LineChart>
</ResponsiveContainer>
注意:
ResponsiveContainer
必须有一个已定义尺寸的父元素,高度必须为数值,不能是百分比。

Static sizing

静态尺寸

Set
width
and
height
directly as pixels or percentages:
jsx
<LineChart data={data} width={600} height={300}>
  {/* chart components */}
</LineChart>
直接设置
width
height
为像素或百分比:
jsx
<LineChart data={data} width={600} height={300}>
  {/* 图表组件 */}
</LineChart>

Axes Configuration

坐标轴配置

XAxis / YAxis Props

XAxis / YAxis 属性

jsx
<XAxis 
  dataKey="name"           // property to display
  type="category"          // "category" or "number"
  domain={[0, 'dataMax']}    // axis range
  tick={{ fill: '#666' }}    // tick styling
  tickFormatter={(value) => `$${value}`}  // format labels
  angle={-45}               // rotate labels
  textAnchor="end"         // text alignment
  height={60}              // extra space for labels
/>
jsx
<XAxis 
  dataKey="name"           // 要显示的属性
  type="category"          // "category"或"number"
  domain={[0, 'dataMax']}    // 坐标轴范围
  tick={{ fill: '#666' }}    // 刻度样式
  tickFormatter={(value) => `$${value}`}  // 格式化标签
  angle={-45}               // 旋转标签
  textAnchor="end"         // 文本对齐方式
  height={60}              // 标签的额外空间
/>

Axis Types

坐标轴类型

  • Category axis (default for X): Treats values as discrete labels
  • Number axis (default for Y): Treats values as continuous scale
  • 分类轴(X轴默认):将值视为离散标签
  • 数值轴(Y轴默认):将值视为连续刻度

Custom Domains

自定义范围

Control axis range:
jsx
// Fixed range
<YAxis domain={[0, 100]} />

// Auto with padding
<YAxis domain={[0, 'auto']} />

// Data-based with overflow allowed
<YAxis domain={[0, 'dataMax + 100']} allowDataOverflow />

// Logarithmic scale
<YAxis type="number" scale="log" domain={['auto', 'auto']} />
控制坐标轴范围:
jsx
// 固定范围
<YAxis domain={[0, 100]} />

// 自动带内边距
<YAxis domain={[0, 'auto']} />

// 基于数据并允许溢出
<YAxis domain={[0, 'dataMax + 100']} allowDataOverflow />

// 对数刻度
<YAxis type="number" scale="log" domain={['auto', 'auto']} />

Customization

自定义设置

Custom Tooltip

自定义提示框

jsx
const CustomTooltip = ({ active, payload, label }) => {
  if (active && payload && payload.length) {
    return (
      <div className="custom-tooltip">
        <p className="label">{`${label}`}</p>
        <p className="intro">{`Sales: ${payload[0].value}`}</p>
        <p className="desc">Additional info...</p>
      </div>
    );
  }
  return null;
};

<Tooltip content={<CustomTooltip />} />
jsx
const CustomTooltip = ({ active, payload, label }) => {
  if (active && payload && payload.length) {
    return (
      <div className="custom-tooltip">
        <p className="label">{`${label}`}</p>
        <p className="intro">{`Sales: ${payload[0].value}`}</p>
        <p className="desc">Additional info...</p>
      </div>
    );
  }
  return null;
};

<Tooltip content={<CustomTooltip />} />

Custom Legend

自定义图例

jsx
const CustomLegend = ({ payload }) => (
  <ul>
    {payload.map((entry, index) => (
      <li key={`item-${index}`} style={{ color: entry.color }}>
        {entry.value}
      </li>
    ))}
  </ul>
);

<Legend content={<CustomLegend />} />
jsx
const CustomLegend = ({ payload }) => (
  <ul>
    {payload.map((entry, index) => (
      <li key={`item-${index}`} style={{ color: entry.color }}>
        {entry.value}
      </li>
    ))}
  </ul>
);

<Legend content={<CustomLegend />} />

Custom Shapes

自定义形状

Custom bar shape:
jsx
const CustomBar = (props) => {
  const { x, y, width, height, fill } = props;
  return <path d={`M${x},${y} ...`} fill={fill} />;
};

<Bar shape={<CustomBar />} dataKey="sales" />
// OR
<Bar shape={(props) => <CustomBar {...props} />} dataKey="sales" />
自定义柱状图形状:
jsx
const CustomBar = (props) => {
  const { x, y, width, height, fill } = props;
  return <path d={`M${x},${y} ...`} fill={fill} />;
};

<Bar shape={<CustomBar />} dataKey="sales" />
// 或
<Bar shape={(props) => <CustomBar {...props} />} dataKey="sales" />

Custom Labels

自定义标签

jsx
<Line 
  dataKey="sales" 
  label={{ position: 'top', fill: '#666', fontSize: 12 }}
/>

// Custom label component
<Line 
  dataKey="sales" 
  label={<CustomLabel />}
/>
jsx
<Line 
  dataKey="sales" 
  label={{ position: 'top', fill: '#666', fontSize: 12 }}
/>

// 自定义标签组件
<Line 
  dataKey="sales" 
  label={<CustomLabel />}
/>

Styling

样式设置

Chart styles:
jsx
<LineChart style={{ backgroundColor: '#f5f5f5' }}>
Axis styling:
jsx
<XAxis 
  axisLine={{ stroke: '#666' }}
  tickLine={{ stroke: '#666' }}
  tick={{ fill: '#666', fontSize: 12 }}
/>
Grid styling:
jsx
<CartesianGrid strokeDasharray="3 3" stroke="#e0e0e0" />
图表样式:
jsx
<LineChart style={{ backgroundColor: '#f5f5f5' }}>
坐标轴样式:
jsx
<XAxis 
  axisLine={{ stroke: '#666' }}
  tickLine={{ stroke: '#666' }}
  tick={{ fill: '#666', fontSize: 12 }}
/>
网格样式:
jsx
<CartesianGrid strokeDasharray="3 3" stroke="#e0e0e0" />

Interactions

交互功能

Active Elements and Interaction Control

激活元素与交互控制

The
Tooltip
component controls active element highlighting. Do not use
activeIndex
prop (removed in v3).
Tooltip interaction props:
  • defaultIndex
    : Sets initial highlighted item on render
  • active
    : If true, tooltip remains active after interaction ends
  • trigger
    :
    "hover"
    (default) or
    "click"
    for click-based interaction
  • content
    : Custom content or
    () => null
    to hide tooltip text while keeping highlight
  • cursor
    : Visual cursor in plot area, set to
    false
    to hide
jsx
{/* Click-based interaction with hidden tooltip text */}
<Tooltip trigger="click" content={() => null} cursor={false} />

{/* Default highlighted item on render */}
<Tooltip defaultIndex={2} />
Tooltip
组件控制激活元素的高亮,请勿使用
activeIndex
属性(v3中已移除)。
提示框交互属性:
  • defaultIndex
    : 设置渲染时初始高亮的项
  • active
    : 如果为true,交互结束后提示框保持激活
  • trigger
    :
    "hover"
    (默认)或
    "click"
    ,基于点击的交互
  • content
    : 自定义内容或
    () => null
    以隐藏提示框文本同时保持高亮
  • cursor
    : 绘图区域的可视化光标,设置为
    false
    可隐藏
jsx
{/* 基于点击的交互,隐藏提示框文本 */}
<Tooltip trigger="click" content={() => null} cursor={false} />

{/* 渲染时默认高亮指定项 */}
<Tooltip defaultIndex={2} />

Click Events

点击事件

jsx
<LineChart onClick={(e) => console.log(e)}>
  <Bar 
    dataKey="sales" 
    onClick={(data, index) => console.log('Bar clicked:', data)}
  />
</LineChart>
jsx
<LineChart onClick={(e) => console.log(e)}>
  <Bar 
    dataKey="sales" 
    onClick={(data, index) => console.log('Bar clicked:', data)}
  />
</LineChart>

Synchronized Charts

同步图表

Link multiple charts with
syncId
:
jsx
<LineChart data={data1} syncId="anyId">
  {/* components */}
</LineChart>

<LineChart data={data2} syncId="anyId">
  {/* components - tooltips synchronize */}
</LineChart>
使用
syncId
链接多个图表:
jsx
<LineChart data={data1} syncId="anyId">
  {/* 组件 */}
</LineChart>

<LineChart data={data2} syncId="anyId">
  {/* 组件 - 提示框同步 */}
</LineChart>

Brush for Zooming

缩放刷选

jsx
<LineChart data={data}>
  {/* other components */}
  <Brush dataKey="name" height={30} stroke="#8884d8" />
</LineChart>
jsx
<LineChart data={data}>
  {/* 其他组件 */}
  <Brush dataKey="name" height={30} stroke="#8884d8" />
</LineChart>

Performance Optimization

性能优化

1. Stable References

1. 稳定引用

Use
useMemo
and
useCallback
for props:
jsx
// BAD - new function on every render
<Line dataKey={(entry) => entry.sales * 2} />

// GOOD - stable reference
const dataKey = useCallback((entry) => entry.sales * 2, []);
<Line dataKey={dataKey} />
使用
useMemo
useCallback
处理属性:
jsx
// 错误 - 每次渲染创建新函数
<Line dataKey={(entry) => entry.sales * 2} />

// 正确 - 稳定引用
const dataKey = useCallback((entry) => entry.sales * 2, []);
<Line dataKey={dataKey} />

2. Memoize Components

2. 组件记忆化

jsx
const MemoizedChart = React.memo(({ data }) => (
  <LineChart data={data}>
    {/* components */}
  </LineChart>
));
jsx
const MemoizedChart = React.memo(({ data }) => (
  <LineChart data={data}>
    {/* 组件 */}
  </LineChart>
));

3. Isolate Changing Components

3. 隔离变化的组件

Separate frequently updating components:
jsx
const Chart = () => {
  const [hoveredData, setHoveredData] = useState(null);
  
  return (
    <LineChart>
      {/* Static components */}
      <Line dataKey="sales" />
      
      {/* Dynamic overlay */}
      <ReferenceLine x={hoveredData?.x} stroke="red" />
    </LineChart>
  );
};
分离频繁更新的组件:
jsx
const Chart = () => {
  const [hoveredData, setHoveredData] = useState(null);
  
  return (
    <LineChart>
      {/* 静态组件 */}
      <Line dataKey="sales" />
      
      {/* 动态覆盖层 */}
      <ReferenceLine x={hoveredData?.x} stroke="red" />
    </LineChart>
  );
};

4. Debounce Events

4. 事件防抖

jsx
import { useDebouncedCallback } from 'use-debounce';

const handleMouseMove = useDebouncedCallback((e) => {
  setPosition(e.activeLabel);
}, 10);

<LineChart onMouseMove={handleMouseMove}>
jsx
import { useDebouncedCallback } from 'use-debounce';

const handleMouseMove = useDebouncedCallback((e) => {
  setPosition(e.activeLabel);
}, 10);

<LineChart onMouseMove={handleMouseMove}>

5. Reduce Data Points

5. 减少数据点

For large datasets, consider aggregation:
jsx
// Bin data before rendering
const binnedData = useMemo(() => {
  return d3.bin().value(d => d.x)(rawData);
}, [rawData]);
对于大型数据集,考虑聚合:
jsx
// 渲染前对数据分箱
const binnedData = useMemo(() => {
  return d3.bin().value(d => d.x)(rawData);
}, [rawData]);

Accessibility

无障碍访问

Recharts includes built-in accessibility support:
jsx
<LineChart accessibilityLayer={true}>
  <Line dataKey="sales" name="Monthly Sales" />
</LineChart>
Accessibility is enabled by default. The chart is keyboard navigable and screen reader compatible.
ARIA props:
jsx
<LineChart role="img" aria-label="Sales chart showing monthly revenue">
Recharts内置无障碍访问支持:
jsx
<LineChart accessibilityLayer={true}>
  <Line dataKey="sales" name="Monthly Sales" />
</LineChart>
无障碍访问默认启用,图表支持键盘导航和屏幕阅读器兼容。
ARIA属性:
jsx
<LineChart role="img" aria-label="Sales chart showing monthly revenue">

Common Patterns

常见模式

Multiple Data Series

多数据系列

jsx
<LineChart data={data}>
  <XAxis dataKey="month" />
  <YAxis />
  <Tooltip />
  <Legend />
  <Line type="monotone" dataKey="productA" name="Product A" stroke="#8884d8" />
  <Line type="monotone" dataKey="productB" name="Product B" stroke="#82ca9d" />
  <Line type="monotone" dataKey="productC" name="Product C" stroke="#ffc658" />
</LineChart>
jsx
<LineChart data={data}>
  <XAxis dataKey="month" />
  <YAxis />
  <Tooltip />
  <Legend />
  <Line type="monotone" dataKey="productA" name="Product A" stroke="#8884d8" />
  <Line type="monotone" dataKey="productB" name="Product B" stroke="#82ca9d" />
  <Line type="monotone" dataKey="productC" name="Product C" stroke="#ffc658" />
</LineChart>

Horizontal Bar Chart

水平柱状图

jsx
<BarChart layout="vertical" data={data}>
  <XAxis type="number" />
  <YAxis type="category" dataKey="name" />
  <Bar dataKey="value" />
</BarChart>
jsx
<BarChart layout="vertical" data={data}>
  <XAxis type="number" />
  <YAxis type="category" dataKey="name" />
  <Bar dataKey="value" />
</BarChart>

Donut Chart

环形图

jsx
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

<PieChart>
  <Pie
    data={data}
    innerRadius={60}
    outerRadius={80}
    paddingAngle={5}
    dataKey="value"
    shape={(props) => <Sector {...props} fill={COLORS[props.index % COLORS.length]} />}
  />
</PieChart>
Note:
Cell
component is deprecated and will be removed in Recharts 4.0. Use the
shape
prop on
Bar
,
Pie
,
Scatter
, etc. instead.
jsx
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

<PieChart>
  <Pie
    data={data}
    innerRadius={60}
    outerRadius={80}
    paddingAngle={5}
    dataKey="value"
    shape={(props) => <Sector {...props} fill={COLORS[props.index % COLORS.length]} />}
  />
</PieChart>
注意:
Cell
组件已弃用,将在Recharts 4.0中移除,请在
Bar
Pie
Scatter
等组件上使用
shape
属性替代。

Reference Lines/Areas

参考线/参考区域

jsx
<LineChart data={data}>
  {/* ... */}
  <ReferenceLine y={5000} label="Target" stroke="red" strokeDasharray="3 3" />
  <ReferenceArea x1="Jan" x2="Mar" fill="#8884d8" fillOpacity={0.1} />
</LineChart>
jsx
<LineChart data={data}>
  {/* ... */}
  <ReferenceLine y={5000} label="Target" stroke="red" strokeDasharray="3 3" />
  <ReferenceArea x1="Jan" x2="Mar" fill="#8884d8" fillOpacity={0.1} />
</LineChart>

Error Bars

误差线

jsx
<ScatterChart>
  <Scatter data={data}>
    <ErrorBar dataKey="errorX" width={4} strokeWidth={2} />
    <ErrorBar dataKey="errorY" width={4} strokeWidth={2} direction="y" />
  </Scatter>
</ScatterChart>
jsx
<ScatterChart>
  <Scatter data={data}>
    <ErrorBar dataKey="errorX" width={4} strokeWidth={2} />
    <ErrorBar dataKey="errorY" width={4} strokeWidth={2} direction="y" />
  </Scatter>
</ScatterChart>

Integration Patterns

集成模式

With State Management

与状态管理结合

jsx
const SalesChart = () => {
  const [timeRange, setTimeRange] = useState('month');
  const data = useSelector(state => selectSalesData(state, timeRange));
  
  return (
    <ResponsiveContainer>
      <LineChart data={data}>
        {/* components */}
      </LineChart>
    </ResponsiveContainer>
  );
};
jsx
const SalesChart = () => {
  const [timeRange, setTimeRange] = useState('month');
  const data = useSelector(state => selectSalesData(state, timeRange));
  
  return (
    <ResponsiveContainer>
      <LineChart data={data}>
        {/* 组件 */}
      </LineChart>
    </ResponsiveContainer>
  );
};

With Real-time Data

实时数据

jsx
const RealtimeChart = () => {
  const [data, setData] = useState([]);
  
  useEffect(() => {
    const interval = setInterval(() => {
      setData(prev => [...prev.slice(-20), newDataPoint]);
    }, 1000);
    return () => clearInterval(interval);
  }, []);
  
  return (
    <LineChart data={data}>
      <XAxis dataKey="time" />
      <YAxis domain={['auto', 'auto']} />
      <Line type="monotone" dataKey="value" isAnimationActive={false} />
    </LineChart>
  );
};
jsx
const RealtimeChart = () => {
  const [data, setData] = useState([]);
  
  useEffect(() => {
    const interval = setInterval(() => {
      setData(prev => [...prev.slice(-20), newDataPoint]);
    }, 1000);
    return () => clearInterval(interval);
  }, []);
  
  return (
    <LineChart data={data}>
      <XAxis dataKey="time" />
      <YAxis domain={['auto', 'auto']} />
      <Line type="monotone" dataKey="value" isAnimationActive={false} />
    </LineChart>
  );
};

Z-Index and Layering (v3.4+)

Z轴索引与分层(v3.4+)

Components render in a default order (grid < axes < chart elements < tooltip/legend). Override with
zIndex
prop:
jsx
<Line dataKey="sales" zIndex={10} />  // Render on top
For components without direct
zIndex
support, wrap in
ZIndexLayer
:
jsx
import { ZIndexLayer } from 'recharts';

<ZIndexLayer zIndex={5}>
  <CustomAnnotation />
</ZIndexLayer>
组件按默认顺序渲染(网格 < 坐标轴 < 图表元素 < 提示框/图例),使用
zIndex
属性覆盖:
jsx
<Line dataKey="sales" zIndex={10} />  // 渲染在顶层
对于不直接支持
zIndex
的组件,使用
ZIndexLayer
包装:
jsx
import { ZIndexLayer } from 'recharts';

<ZIndexLayer zIndex={5}>
  <CustomAnnotation />
</ZIndexLayer>

Coordinate Systems

坐标系

Recharts has three coordinate systems:
  1. Domain coordinates - Data values (e.g.,
    x="March"
    ,
    y=5000
    ). Used by
    ReferenceLine
    ,
    ReferenceDot
    ,
    ReferenceArea
    . Automatically converted to pixels.
  2. Pixel coordinates - Positions relative to chart viewBox. Used for custom SVG shapes. Access via
    usePlotArea()
    ,
    useOffset()
    ,
    useChartWidth()
    hooks.
  3. Mouse event coordinates - Browser viewport coordinates. Convert with
    getRelativeCoordinate(event, element)
    .
Converting between systems:
  • Data to pixels:
    useXAxisScale()
    ,
    useYAxisScale()
  • Pixels to data:
    useXAxisInverseScale()
    ,
    useYAxisInverseScale()
Recharts有三种坐标系:
  1. 域坐标 - 数据值(例如
    x="March"
    ,
    y=5000
    ),用于
    ReferenceLine
    ReferenceDot
    ReferenceArea
    ,自动转换为像素。
  2. 像素坐标 - 相对于图表视口的位置,用于自定义SVG形状,通过
    usePlotArea()
    useOffset()
    useChartWidth()
    钩子访问。
  3. 鼠标事件坐标 - 浏览器视口坐标,使用
    getRelativeCoordinate(event, element)
    转换。
坐标系转换:
  • 数据转像素:
    useXAxisScale()
    ,
    useYAxisScale()
  • 像素转数据:
    useXAxisInverseScale()
    ,
    useYAxisInverseScale()

Troubleshooting

故障排除

Chart Not Rendering

图表未渲染

  • Ensure
    ResponsiveContainer
    has a parent with defined dimensions
  • Check that height is a number (not percentage in ResponsiveContainer)
  • Verify data is an array of objects
  • 确保
    ResponsiveContainer
    有已定义尺寸的父元素
  • 检查高度是否为数值(ResponsiveContainer中不能是百分比)
  • 验证数据是否为对象数组

Tooltip Not Showing

提示框未显示

  • Ensure Tooltip component is included
  • Check that dataKey values exist in data objects
  • 确保已包含Tooltip组件
  • 检查dataKey值是否存在于数据对象中

Axis Labels Overlapping

坐标轴标签重叠

  • Rotate labels:
    <XAxis angle={-45} textAnchor="end" height={80} />
  • Use interval:
    <XAxis interval={0} />
    (0 = show all, 'preserveStartEnd' = auto)
  • 旋转标签:
    <XAxis angle={-45} textAnchor="end" height={80} />
  • 使用间隔:
    <XAxis interval={0} />
    (0 = 显示所有,'preserveStartEnd' = 自动)

Animation Issues

动画问题

  • Disable:
    <Line isAnimationActive={false} />
  • Reduce duration:
    <Line animationDuration={500} />
  • 禁用动画:
    <Line isAnimationActive={false} />
  • 减少动画时长:
    <Line animationDuration={500} />

Resources

资源

References

参考文档

  • API Reference - Complete component props and API details
  • Examples - Common chart patterns and code snippets
  • Best Practices - Performance and design guidelines
  • API Reference - 完整的组件属性和API详情
  • Examples - 常见图表模式和代码片段
  • Best Practices - 性能和设计指南

External Resources

外部资源