recharts
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRecharts
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 rechartsbash
npm install recharts2. 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 props to map object properties to chart components:
dataKey- - maps to the revenue property
dataKey="revenue" - - function for computed values
dataKey={(entry) => entry.revenue - entry.expenses}
Recharts要求数据为对象数组,每个对象代表一个数据点:
javascript
const data = [
{ month: 'Jan', revenue: 4000, expenses: 2400 },
{ month: 'Feb', revenue: 3000, expenses: 1398 },
];使用属性将对象属性映射到图表组件:
dataKey- - 映射到revenue属性
dataKey="revenue" - - 用于计算值的函数
dataKey={(entry) => entry.revenue - entry.expenses}
Component Composition
组件组合
Charts are built by nesting specialized components:
Sizing: Use the prop (v3.3+), wrapper, or set / directly
responsiveResponsiveContainerwidthheightChart types (choose one):
- - Line and area visualizations
LineChart - - Bar and column charts
BarChart - - Stacked and filled area charts
AreaChart - - Pie and donut charts
PieChart - - Scatter plots and bubble charts
ScatterChart - - Mixed chart types
ComposedChart - - Radar/spider charts
RadarChart - - Circular bar charts
RadialBarChart
Common child components:
- /
XAxis- Axis configurationYAxis - - Grid lines
CartesianGrid - - Hover information
Tooltip - - Series identification
Legend - /
Line/Bar/Area- Data series visualizationPie
通过嵌套专用组件来构建图表:
尺寸设置:使用属性(v3.3+)、包装器,或直接设置/
responsiveResponsiveContainerwidthheight图表类型(选择其一):
- - 折线和面积可视化
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:
- : "monotone" (smooth), "linear", "step", "natural"
type - : line color
stroke - : line thickness
strokeWidth - : point styling (set to
dotto hide)false - : hovered point styling
activeDot - : true to connect gaps
connectNulls
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>关键属性:
- : "monotone"(平滑)、"linear"(线性)、"step"(阶梯)、"natural"(自然)
type - : 线条颜色
stroke - : 线条粗细
strokeWidth - : 点样式(设置为
dot可隐藏)false - : 悬停点样式
activeDot - : 设置为true可连接数据间隙
connectNulls
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:
- : bar color
fill - : rounded corners [topLeft, topRight, bottomRight, bottomLeft] or single number for all corners
radius - : fixed bar width
barSize - : group bars into stacks
stackId - : custom bar shape (function or element)
shape
Stacked bars:
jsx
<Bar dataKey="sales" stackId="a" fill="#8884d8" />
<Bar dataKey="profit" stackId="a" fill="#82ca9d" />Rounded stacked bars (use to round the whole stack):
BarStackjsx
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" />圆角堆叠柱状图(使用为整个堆叠设置圆角):
BarStackjsx
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:
- : creates donut chart when > 0
innerRadius - : pie size
outerRadius - : gap between slices
paddingAngle - /
startAngle: partial pie (default: 0 to 360)endAngle - : shows values on slices
label - : custom render for each slice (replaces deprecated
shapecomponent)Cell
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>关键属性:
- : 大于0时创建环形图
innerRadius - : 饼图大小
outerRadius - : 扇区间隙
paddingAngle - /
startAngle: 部分饼图(默认:0到360)endAngle - : 在扇区上显示数值
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)
responsive选项1: responsive
属性(Recharts 3.3+,推荐)
responsiveSet on the chart itself. Uses standard CSS sizing rules:
responsivejsx
<LineChart data={data} width="100%" height={300} responsive>
{/* chart components */}
</LineChart>Works with flexbox and CSS grid layouts. Also supports CSS props:
stylejsx
<LineChart data={data} responsive style={{ maxWidth: 800, width: '100%', aspectRatio: '16/9' }}>
{/* chart components */}
</LineChart>在图表本身设置,使用标准CSS尺寸规则:
responsivejsx
<LineChart data={data} width="100%" height={300} responsive>
{/* 图表组件 */}
</LineChart>适用于flexbox和CSS网格布局,也支持CSS 属性:
stylejsx
<LineChart data={data} responsive style={{ maxWidth: 800, width: '100%', aspectRatio: '16/9' }}>
{/* 图表组件 */}
</LineChart>Option 2: ResponsiveContainer
(older versions)
ResponsiveContainer选项2: ResponsiveContainer
(旧版本)
ResponsiveContainerFor Recharts < 3.3, wrap chart in :
ResponsiveContainerjsx
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
{/* chart components */}
</LineChart>
</ResponsiveContainer>Critical: must have a parent with defined dimensions. Height must be a number, not a percentage.
ResponsiveContainer对于Recharts < 3.3,使用包装图表:
ResponsiveContainerjsx
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
{/* 图表组件 */}
</LineChart>
</ResponsiveContainer>注意: 必须有一个已定义尺寸的父元素,高度必须为数值,不能是百分比。
ResponsiveContainerStatic sizing
静态尺寸
Set and directly as pixels or percentages:
widthheightjsx
<LineChart data={data} width={600} height={300}>
{/* chart components */}
</LineChart>直接设置和为像素或百分比:
widthheightjsx
<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 component controls active element highlighting. Do not use prop (removed in v3).
TooltipactiveIndexTooltip interaction props:
- : Sets initial highlighted item on render
defaultIndex - : If true, tooltip remains active after interaction ends
active - :
trigger(default) or"hover"for click-based interaction"click" - : Custom content or
contentto hide tooltip text while keeping highlight() => null - : Visual cursor in plot area, set to
cursorto hidefalse
jsx
{/* Click-based interaction with hidden tooltip text */}
<Tooltip trigger="click" content={() => null} cursor={false} />
{/* Default highlighted item on render */}
<Tooltip defaultIndex={2} />TooltipactiveIndex提示框交互属性:
- : 设置渲染时初始高亮的项
defaultIndex - : 如果为true,交互结束后提示框保持激活
active - :
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 :
syncIdjsx
<LineChart data={data1} syncId="anyId">
{/* components */}
</LineChart>
<LineChart data={data2} syncId="anyId">
{/* components - tooltips synchronize */}
</LineChart>使用链接多个图表:
syncIdjsx
<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 and for props:
useMemouseCallbackjsx
// 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} />使用和处理属性:
useMemouseCallbackjsx
// 错误 - 每次渲染创建新函数
<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:component is deprecated and will be removed in Recharts 4.0. Use theCellprop onshape,Bar,Pie, etc. instead.Scatter
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>注意:组件已弃用,将在Recharts 4.0中移除,请在Cell、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 prop:
zIndexjsx
<Line dataKey="sales" zIndex={10} /> // Render on topFor components without direct support, wrap in :
zIndexZIndexLayerjsx
import { ZIndexLayer } from 'recharts';
<ZIndexLayer zIndex={5}>
<CustomAnnotation />
</ZIndexLayer>组件按默认顺序渲染(网格 < 坐标轴 < 图表元素 < 提示框/图例),使用属性覆盖:
zIndexjsx
<Line dataKey="sales" zIndex={10} /> // 渲染在顶层对于不直接支持的组件,使用包装:
zIndexZIndexLayerjsx
import { ZIndexLayer } from 'recharts';
<ZIndexLayer zIndex={5}>
<CustomAnnotation />
</ZIndexLayer>Coordinate Systems
坐标系
Recharts has three coordinate systems:
- Domain coordinates - Data values (e.g., ,
x="March"). Used byy=5000,ReferenceLine,ReferenceDot. Automatically converted to pixels.ReferenceArea - Pixel coordinates - Positions relative to chart viewBox. Used for custom SVG shapes. Access via ,
usePlotArea(),useOffset()hooks.useChartWidth() - 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有三种坐标系:
- 域坐标 - 数据值(例如,
x="March"),用于y=5000、ReferenceLine、ReferenceDot,自动转换为像素。ReferenceArea - 像素坐标 - 相对于图表视口的位置,用于自定义SVG形状,通过、
usePlotArea()、useOffset()钩子访问。useChartWidth() - 鼠标事件坐标 - 浏览器视口坐标,使用转换。
getRelativeCoordinate(event, element)
坐标系转换:
- 数据转像素: ,
useXAxisScale()useYAxisScale() - 像素转数据: ,
useXAxisInverseScale()useYAxisInverseScale()
Troubleshooting
故障排除
Chart Not Rendering
图表未渲染
- Ensure has a parent with defined dimensions
ResponsiveContainer - 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: (0 = show all, 'preserveStartEnd' = auto)
<XAxis interval={0} />
- 旋转标签:
<XAxis angle={-45} textAnchor="end" height={80} /> - 使用间隔: (0 = 显示所有,'preserveStartEnd' = 自动)
<XAxis interval={0} />
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 - 性能和设计指南