npx skills add https://github.com/ansanabria/skills --skill recharts基于 D3 构建的 React 图表库,用于可组合、声明式的数据可视化。
npm install recharts
所有 Recharts 图表都遵循相同的模式:
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 期望数据为对象数组。每个对象代表一个数据点:
const data = [
{ month: 'Jan', revenue: 4000, expenses: 2400 },
{ month: 'Feb', revenue: 3000, expenses: 1398 },
];
使用 dataKey 属性将对象属性映射到图表组件:
React charting library built on top of D3 for composable, declarative data visualization.
npm install recharts
All Recharts charts follow the same pattern:
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 expects data as an array of objects. Each object represents a data point:
const data = [
{ month: 'Jan', revenue: 4000, expenses: 2400 },
{ month: 'Feb', revenue: 3000, expenses: 1398 },
];
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
dataKey="revenue" - 映射到 revenue 属性dataKey={(entry) => entry.revenue - entry.expenses} - 用于计算值的函数图表通过嵌套专用组件构建:
尺寸设置 :使用 responsive 属性(v3.3+)、ResponsiveContainer 包装器或直接设置 width/height
图表类型(选择一种):
LineChart - 折线图和面积图可视化BarChart - 条形图和柱状图AreaChart - 堆叠和填充面积图PieChart - 饼图和环形图ScatterChart - 散点图和气泡图ComposedChart - 混合图表类型RadarChart - 雷达图/蜘蛛图RadialBarChart - 圆形条形图常用子组件:
XAxis / YAxis - 坐标轴配置CartesianGrid - 网格线Tooltip - 悬停信息Legend - 系列标识Line / Bar / Area / Pie - 数据系列可视化<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 以连接间隙<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>
堆叠面积图:
<Area type="monotone" dataKey="sales" stackId="1" stroke="#8884d8" fill="#8884d8" />
<Area type="monotone" dataKey="profit" stackId="1" stroke="#82ca9d" fill="#82ca9d" />
<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: 自定义条形形状(函数或元素)堆叠条形图:
<Bar dataKey="sales" stackId="a" fill="#8884d8" />
<Bar dataKey="profit" stackId="a" fill="#82ca9d" />
圆角堆叠条形图(使用 BarStack 来圆化整个堆叠):
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>
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 组件)<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>
混合多种图表类型:
<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 属性(Recharts 3.3+,推荐)在图表本身上设置 responsive。使用标准 CSS 尺寸规则:
<LineChart data={data} width="100%" height={300} responsive>
{/* chart components */}
</LineChart>
适用于 flexbox 和 CSS 网格布局。也支持 CSS style 属性:
<LineChart data={data} responsive style={{ maxWidth: 800, width: '100%', aspectRatio: '16/9' }}>
{/* chart components */}
</LineChart>
ResponsiveContainer(旧版本)对于 Recharts < 3.3,将图表包装在 ResponsiveContainer 中:
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
{/* chart components */}
</LineChart>
</ResponsiveContainer>
关键:ResponsiveContainer 必须有一个定义了尺寸的父元素。高度必须是数字,不能是百分比。
直接设置 width 和 height 为像素或百分比:
<LineChart data={data} width={600} height={300}>
{/* chart components */}
</LineChart>
<XAxis
dataKey="name" // 要显示的属性
type="category" // "category" 或 "number"
domain={[0, 'dataMax']} // 坐标轴范围
tick={{ fill: '#666' }} // 刻度样式
tickFormatter={(value) => `$${value}`} // 格式化标签
angle={-45} // 旋转标签
textAnchor="end" // 文本对齐
height={60} // 标签的额外空间
/>
控制坐标轴范围:
// 固定范围
<YAxis domain={[0, 100]} />
// 自动带填充
<YAxis domain={[0, 'auto']} />
// 基于数据,允许溢出
<YAxis domain={[0, 'dataMax + 100']} allowDataOverflow />
// 对数比例尺
<YAxis type="number" scale="log" domain={['auto', 'auto']} />
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 />} />
const CustomLegend = ({ payload }) => (
<ul>
{payload.map((entry, index) => (
<li key={`item-${index}`} style={{ color: entry.color }}>
{entry.value}
</li>
))}
</ul>
);
<Legend content={<CustomLegend />} />
自定义条形形状:
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" />
<Line
dataKey="sales"
label={{ position: 'top', fill: '#666', fontSize: 12 }}
/>
// 自定义标签组件
<Line
dataKey="sales"
label={<CustomLabel />}
/>
图表样式:
<LineChart style={{ backgroundColor: '#f5f5f5' }}>
坐标轴样式:
<XAxis
axisLine={{ stroke: '#666' }}
tickLine={{ stroke: '#666' }}
tick={{ fill: '#666', fontSize: 12 }}
/>
网格样式:
<CartesianGrid strokeDasharray="3 3" stroke="#e0e0e0" />
Tooltip 组件控制活动元素高亮。不要使用 activeIndex 属性(已在 v3 中移除)。
工具提示交互属性:
defaultIndex: 在渲染时设置初始高亮项
active: 如果为 true,交互结束后工具提示保持活动状态
trigger: "hover"(默认)或 "click" 用于基于点击的交互
content: 自定义内容或 () => null 以在保持高亮的同时隐藏工具提示文本
cursor: 绘图区域中的视觉光标,设置为 false 以隐藏
{/* 基于点击的交互,隐藏工具提示文本 */} <Tooltip trigger="click" content={() => null} cursor={false} />
{/* 渲染时默认高亮项 */} <Tooltip defaultIndex={2} />
<LineChart onClick={(e) => console.log(e)}>
<Bar
dataKey="sales"
onClick={(data, index) => console.log('Bar clicked:', data)}
/>
</LineChart>
使用 syncId 链接多个图表:
<LineChart data={data1} syncId="anyId">
{/* components */}
</LineChart>
<LineChart data={data2} syncId="anyId">
{/* components - tooltips synchronize */}
</LineChart>
<LineChart data={data}>
{/* other components */}
<Brush dataKey="name" height={30} stroke="#8884d8" />
</LineChart>
对属性使用 useMemo 和 useCallback:
// 不好 - 每次渲染都创建新函数
<Line dataKey={(entry) => entry.sales * 2} />
// 好 - 稳定的引用
const dataKey = useCallback((entry) => entry.sales * 2, []);
<Line dataKey={dataKey} />
const MemoizedChart = React.memo(({ data }) => (
<LineChart data={data}>
{/* components */}
</LineChart>
));
分离频繁更新的组件:
const Chart = () => {
const [hoveredData, setHoveredData] = useState(null);
return (
<LineChart>
{/* 静态组件 */}
<Line dataKey="sales" />
{/* 动态覆盖层 */}
<ReferenceLine x={hoveredData?.x} stroke="red" />
</LineChart>
);
};
import { useDebouncedCallback } from 'use-debounce';
const handleMouseMove = useDebouncedCallback((e) => {
setPosition(e.activeLabel);
}, 10);
<LineChart onMouseMove={handleMouseMove}>
对于大型数据集,考虑聚合:
// 在渲染前分箱数据
const binnedData = useMemo(() => {
return d3.bin().value(d => d.x)(rawData);
}, [rawData]);
Recharts 包含内置的可访问性支持:
<LineChart accessibilityLayer={true}>
<Line dataKey="sales" name="Monthly Sales" />
</LineChart>
默认启用可访问性。图表支持键盘导航和屏幕阅读器兼容。
ARIA 属性:
<LineChart role="img" aria-label="Sales chart showing monthly revenue">
<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>
<BarChart layout="vertical" data={data}>
<XAxis type="number" />
<YAxis type="category" dataKey="name" />
<Bar dataKey="value" />
</BarChart>
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属性。
<LineChart data={data}>
{/* ... */}
<ReferenceLine y={5000} label="Target" stroke="red" strokeDasharray="3 3" />
<ReferenceArea x1="Jan" x2="Mar" fill="#8884d8" fillOpacity={0.1} />
</LineChart>
<ScatterChart>
<Scatter data={data}>
<ErrorBar dataKey="errorX" width={4} strokeWidth={2} />
<ErrorBar dataKey="errorY" width={4} strokeWidth={2} direction="y" />
</Scatter>
</ScatterChart>
const SalesChart = () => {
const [timeRange, setTimeRange] = useState('month');
const data = useSelector(state => selectSalesData(state, timeRange));
return (
<ResponsiveContainer>
<LineChart data={data}>
{/* components */}
</LineChart>
</ResponsiveContainer>
);
};
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>
);
};
组件按默认顺序渲染(网格 < 坐标轴 < 图表元素 < 工具提示/图例)。使用 zIndex 属性覆盖:
<Line dataKey="sales" zIndex={10} /> // 在顶部渲染
对于没有直接 zIndex 支持的组件,包装在 ZIndexLayer 中:
import { ZIndexLayer } from 'recharts';
<ZIndexLayer zIndex={5}>
<CustomAnnotation />
</ZIndexLayer>
Recharts 有三种坐标系:
x="March"、y=5000)。由 ReferenceLine、ReferenceDot、ReferenceArea 使用。自动转换为像素。usePlotArea()、useOffset()、useChartWidth() 钩子访问。getRelativeCoordinate(event, element) 转换。系统间转换:
useXAxisScale()、useYAxisScale()useXAxisInverseScale()、useYAxisInverseScale()ResponsiveContainer 有一个定义了尺寸的父元素<XAxis angle={-45} textAnchor="end" height={80} /><XAxis interval={0} />(0 = 显示所有,'preserveStartEnd' = 自动)<Line isAnimationActive={false} /><Line animationDuration={500} />每周安装数
66
仓库
首次出现
2026年2月17日
安全审计
已安装于
cursor64
github-copilot63
opencode63
gemini-cli62
codex62
kimi-cli60
Use dataKey props to map object properties to chart components:
dataKey="revenue" - maps to the revenue propertydataKey={(entry) => entry.revenue - entry.expenses} - function for computed valuesCharts 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 visualizationsBarChart - Bar and column chartsAreaChart - Stacked and filled area chartsPieChart - Pie and donut chartsScatterChart - Scatter plots and bubble chartsComposedChart - Mixed chart typesRadarChart - Radar/spider chartsRadialBarChart - Circular bar chartsCommon child components :
XAxis / YAxis - Axis configurationCartesianGrid - Grid linesTooltip - Hover informationLegend - Series identificationLine / Bar / Area / Pie - Data series visualization<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 colorstrokeWidth: line thicknessdot: point styling (set to false to hide)activeDot: hovered point stylingconnectNulls: true to connect gaps<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 :
<Area type="monotone" dataKey="sales" stackId="1" stroke="#8884d8" fill="#8884d8" />
<Area type="monotone" dataKey="profit" stackId="1" stroke="#82ca9d" fill="#82ca9d" />
<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 colorradius: rounded corners [topLeft, topRight, bottomRight, bottomLeft] or single number for all cornersbarSize: fixed bar widthstackId: group bars into stacksshape: custom bar shape (function or element)Stacked bars :
<Bar dataKey="sales" stackId="a" fill="#8884d8" />
<Bar dataKey="profit" stackId="a" fill="#82ca9d" />
Rounded stacked bars (use BarStack to round the whole stack):
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>
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 > 0outerRadius: pie sizepaddingAngle: gap between slicesstartAngle / endAngle: partial pie (default: 0 to 360)label: shows values on slicesshape: custom render for each slice (replaces deprecated Cell component)<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>
Mix multiple chart types:
<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 prop (Recharts 3.3+, recommended)Set responsive on the chart itself. Uses standard CSS sizing rules:
<LineChart data={data} width="100%" height={300} responsive>
{/* chart components */}
</LineChart>
Works with flexbox and CSS grid layouts. Also supports CSS style props:
<LineChart data={data} responsive style={{ maxWidth: 800, width: '100%', aspectRatio: '16/9' }}>
{/* chart components */}
</LineChart>
ResponsiveContainer (older versions)For Recharts < 3.3, wrap chart in ResponsiveContainer:
<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.
Set width and height directly as pixels or percentages:
<LineChart data={data} width={600} height={300}>
{/* chart components */}
</LineChart>
<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
/>
Control axis range:
// 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']} />
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 />} />
const CustomLegend = ({ payload }) => (
<ul>
{payload.map((entry, index) => (
<li key={`item-${index}`} style={{ color: entry.color }}>
{entry.value}
</li>
))}
</ul>
);
<Legend content={<CustomLegend />} />
Custom bar shape :
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" />
<Line
dataKey="sales"
label={{ position: 'top', fill: '#666', fontSize: 12 }}
/>
// Custom label component
<Line
dataKey="sales"
label={<CustomLabel />}
/>
Chart styles :
<LineChart style={{ backgroundColor: '#f5f5f5' }}>
Axis styling :
<XAxis
axisLine={{ stroke: '#666' }}
tickLine={{ stroke: '#666' }}
tick={{ fill: '#666', fontSize: 12 }}
/>
Grid styling :
<CartesianGrid strokeDasharray="3 3" stroke="#e0e0e0" />
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
{/* Click-based interaction with hidden tooltip text */} <Tooltip trigger="click" content={() => null} cursor={false} />
{/* Default highlighted item on render */} <Tooltip defaultIndex={2} />
<LineChart onClick={(e) => console.log(e)}>
<Bar
dataKey="sales"
onClick={(data, index) => console.log('Bar clicked:', data)}
/>
</LineChart>
Link multiple charts with syncId:
<LineChart data={data1} syncId="anyId">
{/* components */}
</LineChart>
<LineChart data={data2} syncId="anyId">
{/* components - tooltips synchronize */}
</LineChart>
<LineChart data={data}>
{/* other components */}
<Brush dataKey="name" height={30} stroke="#8884d8" />
</LineChart>
Use useMemo and useCallback for props:
// 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} />
const MemoizedChart = React.memo(({ data }) => (
<LineChart data={data}>
{/* components */}
</LineChart>
));
Separate frequently updating components:
const Chart = () => {
const [hoveredData, setHoveredData] = useState(null);
return (
<LineChart>
{/* Static components */}
<Line dataKey="sales" />
{/* Dynamic overlay */}
<ReferenceLine x={hoveredData?.x} stroke="red" />
</LineChart>
);
};
import { useDebouncedCallback } from 'use-debounce';
const handleMouseMove = useDebouncedCallback((e) => {
setPosition(e.activeLabel);
}, 10);
<LineChart onMouseMove={handleMouseMove}>
For large datasets, consider aggregation:
// Bin data before rendering
const binnedData = useMemo(() => {
return d3.bin().value(d => d.x)(rawData);
}, [rawData]);
Recharts includes built-in accessibility support:
<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 :
<LineChart role="img" aria-label="Sales chart showing monthly revenue">
<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>
<BarChart layout="vertical" data={data}>
<XAxis type="number" />
<YAxis type="category" dataKey="name" />
<Bar dataKey="value" />
</BarChart>
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 :
Cellcomponent is deprecated and will be removed in Recharts 4.0. Use theshapeprop onBar,Pie,Scatter, etc. instead.
<LineChart data={data}>
{/* ... */}
<ReferenceLine y={5000} label="Target" stroke="red" strokeDasharray="3 3" />
<ReferenceArea x1="Jan" x2="Mar" fill="#8884d8" fillOpacity={0.1} />
</LineChart>
<ScatterChart>
<Scatter data={data}>
<ErrorBar dataKey="errorX" width={4} strokeWidth={2} />
<ErrorBar dataKey="errorY" width={4} strokeWidth={2} direction="y" />
</Scatter>
</ScatterChart>
const SalesChart = () => {
const [timeRange, setTimeRange] = useState('month');
const data = useSelector(state => selectSalesData(state, timeRange));
return (
<ResponsiveContainer>
<LineChart data={data}>
{/* components */}
</LineChart>
</ResponsiveContainer>
);
};
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>
);
};
Components render in a default order (grid < axes < chart elements < tooltip/legend). Override with zIndex prop:
<Line dataKey="sales" zIndex={10} /> // Render on top
For components without direct zIndex support, wrap in ZIndexLayer:
import { ZIndexLayer } from 'recharts';
<ZIndexLayer zIndex={5}>
<CustomAnnotation />
</ZIndexLayer>
Recharts has three coordinate systems:
x="March", y=5000). Used by ReferenceLine, ReferenceDot, ReferenceArea. Automatically converted to pixels.usePlotArea(), useOffset(), useChartWidth() hooks.getRelativeCoordinate(event, element).Converting between systems :
useXAxisScale(), useYAxisScale()useXAxisInverseScale(), useYAxisInverseScale()ResponsiveContainer has a parent with defined dimensions<XAxis angle={-45} textAnchor="end" height={80} /><XAxis interval={0} /> (0 = show all, 'preserveStartEnd' = auto)<Line isAnimationActive={false} /><Line animationDuration={500} />Weekly Installs
66
Repository
First Seen
Feb 17, 2026
Security Audits
Installed on
cursor64
github-copilot63
opencode63
gemini-cli62
codex62
kimi-cli60
科学数据探索性分析工具:自动检测200+格式,生成EDA报告与可视化建议
975 周安装
pua-ja AI助手:日本职场“詰め”文化驱动的主动式问题解决与任务执行方法论
531 周安装
统计学与数学基础教程 - Python数据科学、机器学习、统计分析核心技能
243 周安装
Reddit帖子分析器 - 深度分析讨论情绪、关键论点与社区共识 | AI驱动
219 周安装
React前端开发指南:Suspense数据获取、性能优化与TypeScript最佳实践
206 周安装
docs-seeker:AI驱动的技术文档智能发现与分析工具,支持llms.txt优先搜索与仓库分析
204 周安装
社交分享按钮实现指南:最佳放置位置、平台URL与图标设计
285 周安装