React 图表库因其能够为开发人员提供强大的数据可视化工具而广受欢迎,从而可以更轻松地创建交互式且具有视觉吸引力的图表,并提供多种选项,例如:
RechartsVictoryVisxNivoReact-visApache EchartsAnt Design Charts- ...
开发人员可以找到完美的库来满足他们的特定需求。
这些图表库的美妙之处在于它们的多功能性。它们满足各种图表要求,从简单的条形图、折线图和饼图,到更复杂的财务数据可视化
由于选项丰富,为您的项目选择最佳的 React 图表库可能具有挑战性。
在本文中,我们将探讨一些最好的 React 图表库,介绍它们的功能、适应性和用户友好性。
Recharts
Recharts 是最受欢迎的 React 图表库之一,拥有庞大的用户群和社区。Recharts 在构建时考虑到了可重用性和灵活性,利用 React 组件和 SVG 为开发人员提供强大且易于使用的图表解决方案。
Recharts 被设计为高度可定制的,允许开发人员创建适合他们需求的图表。
主要特点
- Recharts 提供了一系列关键功能,包括
轻量级组件、原生 SVG支持和简单的自定义。这个图表库提供了各种各样的组件,如折线、条形和饼图,可以很容易地集成到 React 应用程序中。 - Recharts 有效地利用了 React 和 SVG 的功能,简化了创建响应式图表组件的过程,这有助于其广泛普及。
yarn add recharts
示例
DashedLineChart
import React, { PureComponent } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
const data = [
{
name: 'Page A',
uv: 4000,
pv: 2400,
amt: 2400,
},
{
name: 'Page B',
uv: 3000,
pv: 1398,
amt: 2210,
},
{
name: 'Page C',
uv: 2000,
pv: 9800,
amt: 2290,
},
{
name: 'Page D',
uv: 2780,
pv: 3908,
amt: 2000,
},
{
name: 'Page E',
uv: 1890,
pv: 4800,
amt: 2181,
},
{
name: 'Page F',
uv: 2390,
pv: 3800,
amt: 2500,
},
{
name: 'Page G',
uv: 3490,
pv: 4300,
amt: 2100,
},
];
export default class Example extends PureComponent {
static demoUrl = 'https://codesandbox.io/p/sandbox/dashed-line-chart-9rttw2';
render() {
return (
<ResponsiveContainer width="100%" height="100%">
<LineChart
width={500}
height={300}
data={data}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="pv" stroke="#8884d8" strokeDasharray="5 5" />
<Line type="monotone" dataKey="uv" stroke="#82ca9d" strokeDasharray="3 4 5 2" />
</LineChart>
</ResponsiveContainer>
);
}
}
Victory
Victory 是一个多功能的 React 图表库,以其跨平台的灵活性而著称。Victory 同时支持 React 和 React Native,提供一致的 API 和多种图表类型供开发人员选择,使其成为需要跨多个平台部署的项目的热门选择。
yarn add victory
主要特点
- Victory 的主要功能包括跨平台兼容性、可自定义的图表以及对各种图表类型的支持。
- 专注于在 React 和 React Native 之间提供一致的 API,使开发人员能够创建可以轻松集成到各种平台中的图表,从而减少代码重复的需求并简化开发过程。
示例
Victory 组件可用于创建各种数据可视化,例如:
- line charts 折线图
- bar charts 条形图
- pie charts 饼图
- scatter plots 散点图
Polar Cardioid 极地心形
import React from "react";
import { render } from "react-dom";
import { VictoryChart, VictoryPolarAxis, VictoryLine } from "victory";
const colors = [ "#428517", "#77D200", "#D6D305", "#EC8E19", "#C92B05"];
function App() {
return (
<VictoryChart polar
theme={VictoryTheme.material}
domain={{ y: [0, 10] }}
>
<VictoryPolarAxis dependentAxis
style={{ axis: { stroke: "none" } }}
tickFormat={() => ""}
/>
<VictoryPolarAxis
tickValues={[0, Math.PI / 2, Math.PI, (3 * Math.PI) / 2]}
tickFormat={["2π", "π/2", "π", "3π/2"]}
labelPlacement="vertical"
/>
{ [5, 4, 3, 2, 1].map((val, i) => {
return (
<VictoryLine
key={i}
samples={100}
style={{ data: { stroke: colors[i] } }}
y={(d) => val * (1 - Math.cos(d.x))}
/>
);
})}
</VictoryChart>
);
}
render(<App/>);
Nivo
Nivo 因为 React 开发人员提供创造性和可定制的图表解决方案而享有盛誉。凭借其视觉上吸引人的网站和全面的文档,Nivo 使开发人员可以轻松上手并开始使用其广泛的图表样式和设计。
yarn add @nivo/core @nivo/bar
主要特点
Nivo的主要功能包括:
- 支持 SVG、HTML 和 Canvas 图表
- 各种图表类型和动画
- 专注于定制,允许开发人员创建独特且引人入胜的数据可视化
这使 Nivo 有别于其他 React 图表库。鉴于其广泛的图表选项和交互式文档选择,Nivo 是旨在制作视觉上引人入胜的交互式图表的开发人员的令人信服的选择。
Nivo 组件可用于创建各种数据可视化,例如条形图、饼图、散点图、面积凹凸图、折线图、树状图等。
示例
Bar
// install (please try to align the version of installed @nivo packages)
// yarn add @nivo/bar
import { ResponsiveBar } from '@nivo/bar'
// make sure parent container have a defined height when using
// responsive component, otherwise height will be 0 and
// no chart will be rendered.
// website examples showcase many properties,
// you'll often use just a few of them.
const MyResponsiveBar = ({ data /* see data tab */ }) => (
<ResponsiveBar
data={data}
keys={[
'hot dog',
'burger',
'sandwich',
'kebab',
'fries',
'donut'
]}
indexBy="country"
margin={{ top: 50, right: 130, bottom: 50, left: 60 }}
padding={0.3}
valueScale={{ type: 'linear' }}
indexScale={{ type: 'band', round: true }}
colors={{ scheme: 'nivo' }}
defs={[
{
id: 'dots',
type: 'patternDots',
background: 'inherit',
color: '#38bcb2',
size: 4,
padding: 1,
stagger: true
},
{
id: 'lines',
type: 'patternLines',
background: 'inherit',
color: '#eed312',
rotation: -45,
lineWidth: 6,
spacing: 10
}
]}
fill={[
{
match: {
id: 'fries'
},
id: 'dots'
},
{
match: {
id: 'sandwich'
},
id: 'lines'
}
]}
borderColor={{
from: 'color',
modifiers: [
[
'darker',
1.6
]
]
}}
axisTop={null}
axisRight={null}
axisBottom={{
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: 'country',
legendPosition: 'middle',
legendOffset: 32,
truncateTickAt: 0
}}
axisLeft={{
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: 'food',
legendPosition: 'middle',
legendOffset: -40,
truncateTickAt: 0
}}
labelSkipWidth={12}
labelSkipHeight={12}
labelTextColor={{
from: 'color',
modifiers: [
[
'darker',
1.6
]
]
}}
legends={[
{
dataFrom: 'keys',
anchor: 'bottom-right',
direction: 'column',
justify: false,
translateX: 120,
translateY: 0,
itemsSpacing: 2,
itemWidth: 100,
itemHeight: 20,
itemDirection: 'left-to-right',
itemOpacity: 0.85,
symbolSize: 20,
effects: [
{
on: 'hover',
style: {
itemOpacity: 1
}
}
]
}
]}
role="application"
ariaLabel="Nivo bar chart demo"
barAriaLabel={e=>e.id+": "+e.formattedValue+" in country: "+e.indexValue}
/>
)
data数据
[
{
"country": "AD",
"hot dog": 145,
"hot dogColor": "hsl(242, 70%, 50%)",
"burger": 27,
"burgerColor": "hsl(161, 70%, 50%)",
"sandwich": 173,
"sandwichColor": "hsl(102, 70%, 50%)",
"kebab": 68,
"kebabColor": "hsl(202, 70%, 50%)",
"fries": 163,
"friesColor": "hsl(352, 70%, 50%)",
"donut": 187,
"donutColor": "hsl(136, 70%, 50%)"
},
{
"country": "AE",
"hot dog": 11,
"hot dogColor": "hsl(202, 70%, 50%)",
"burger": 122,
"burgerColor": "hsl(323, 70%, 50%)",
"sandwich": 101,
"sandwichColor": "hsl(318, 70%, 50%)",
"kebab": 139,
"kebabColor": "hsl(0, 70%, 50%)",
"fries": 84,
"friesColor": "hsl(26, 70%, 50%)",
"donut": 28,
"donutColor": "hsl(192, 70%, 50%)"
},
{
"country": "AF",
"hot dog": 103,
"hot dogColor": "hsl(293, 70%, 50%)",
"burger": 196,
"burgerColor": "hsl(220, 70%, 50%)",
"sandwich": 129,
"sandwichColor": "hsl(238, 70%, 50%)",
"kebab": 170,
"kebabColor": "hsl(273, 70%, 50%)",
"fries": 82,
"friesColor": "hsl(328, 70%, 50%)",
"donut": 0,
"donutColor": "hsl(116, 70%, 50%)"
},
{
"country": "AG",
"hot dog": 121,
"hot dogColor": "hsl(264, 70%, 50%)",
"burger": 189,
"burgerColor": "hsl(52, 70%, 50%)",
"sandwich": 161,
"sandwichColor": "hsl(300, 70%, 50%)",
"kebab": 196,
"kebabColor": "hsl(262, 70%, 50%)",
"fries": 79,
"friesColor": "hsl(10, 70%, 50%)",
"donut": 148,
"donutColor": "hsl(113, 70%, 50%)"
},
{
"country": "AI",
"hot dog": 44,
"hot dogColor": "hsl(352, 70%, 50%)",
"burger": 156,
"burgerColor": "hsl(16, 70%, 50%)",
"sandwich": 157,
"sandwichColor": "hsl(324, 70%, 50%)",
"kebab": 35,
"kebabColor": "hsl(81, 70%, 50%)",
"fries": 148,
"friesColor": "hsl(354, 70%, 50%)",
"donut": 158,
"donutColor": "hsl(151, 70%, 50%)"
},
{
"country": "AL",
"hot dog": 48,
"hot dogColor": "hsl(253, 70%, 50%)",
"burger": 67,
"burgerColor": "hsl(93, 70%, 50%)",
"sandwich": 142,
"sandwichColor": "hsl(284, 70%, 50%)",
"kebab": 81,
"kebabColor": "hsl(337, 70%, 50%)",
"fries": 173,
"friesColor": "hsl(347, 70%, 50%)",
"donut": 114,
"donutColor": "hsl(284, 70%, 50%)"
},
{
"country": "AM",
"hot dog": 177,
"hot dogColor": "hsl(268, 70%, 50%)",
"burger": 82,
"burgerColor": "hsl(130, 70%, 50%)",
"sandwich": 47,
"sandwichColor": "hsl(204, 70%, 50%)",
"kebab": 0,
"kebabColor": "hsl(255, 70%, 50%)",
"fries": 40,
"friesColor": "hsl(240, 70%, 50%)",
"donut": 127,
"donutColor": "hsl(212, 70%, 50%)"
}
]
React-vis
react-vis (uber.github.io) 官方文档
React-vis 是一个用户友好的 React 图表库,它提供了各种常见的图表类型和易于使用的组件。React-vis 由 Uber 开发,因其视觉上令人愉悦的图表和全面的文档而获得认可,使开发人员能够快速上手并开始使用该库。
yarn add react-vis
主要特点
- React-vis 的主要功能包括广泛的图表类型、响应式设计和易于定制。
- React-vis 专注于用户友好性,为开发人员提供了一个可访问的解决方案,用于创建具有视觉吸引力和交互式的数据可视化。
示例
其图表类型范围涵盖各种选项,例如:
- heat maps 热图
- scatterplots 散点图
- contour plots 等值线图
- hexagon heatmaps Hexagon 热图
- pie and donut charts 饼图和圆环图
- sunbursts 旭日纹
- radar charts 雷达图
- parallel coordinates 平行坐标
- tree maps 树状图
Basic Radar Chart
import React from 'react';
import {format} from 'd3-format'; // d3-format 数据的格式化和解析
import { RadarChart } from 'react-vis';
const DATA = [
{
name: 'Mercedes',
mileage: 7,
price: 10,
safety: 8,
performance: 9,
interior: 7,
warranty: 7
},
{
name: 'Honda',
mileage: 8,
price: 6,
safety: 9,
performance: 6,
interior: 3,
warranty: 9
},
{
name: 'Chevrolet',
mileage: 5,
price: 4,
safety: 6,
performance: 4,
interior: 5,
warranty: 6
}
];
const basicFormat = format('.2r');
const wideFormat = format('.3r');
export default function BasicRadarChart(props) {
return (
<RadarChart
data={DATA}
tickFormat={t => wideFormat(t)}
startingAngle={0}
domains={[
{name: 'mileage', domain: [0, 10]},
{
name: 'price',
domain: [2, 16],
tickFormat: t => `$${basicFormat(t)}`,
getValue: d => d.price
},
{name: 'safety', domain: [5, 10], getValue: d => d.safety},
{name: 'performance', domain: [0, 10], getValue: d => d.performance},
{name: 'interior', domain: [0, 7], getValue: d => d.interior},
{name: 'warranty', domain: [10, 2], getValue: d => d.warranty}
]}
width={400}
height={300}
/>
);
}
Visx
由 Airbnb 开发的 Visx 是一个强大的 React 图表库,它通过集成 React 和 D3.js 的优点结合了两全其美。这种组合使开发人员能够利用 D3.js 的强大功能进行数据操作和计算,同时利用 React 基于组件的架构进行渲染。
npm install --save @visx/mock-data @visx/group @visx/shape @visx/scale
主要特点
- Visx 的主要功能包括低级图形组件、易于重用和模块化设计。通过提供一组低级可视化组件,Visx 允许开发人员创建自定义且极具表现力的图表,同时利用 React 基于组件的架构。
- 这种方法提供了高度的灵活性和定制性,使 Visx 成为需要更好地控制其数据可视化的开发人员的有吸引力的选择。
示例
借助 Visx,开发人员可以创建各种自定义数据可视化,例如具有自定义轴的折线图、带有自定义标签的交互式条形图以及具有自定义颜色的堆积条形图。
React 和 D3.js 的强大组合使开发人员能够构建复杂的、高度可定制的数据可视化,满足各种 react 项目需求。
Streamgraph
/* eslint-disable react-hooks/rules-of-hooks */
/**
* Inspired by Mike Bostock's Streamgraph & Lee Byron’s test data generator:
* https://bl.ocks.org/mbostock/4060954
*/
import React from 'react';
import { Stack } from '@visx/shape';
import { PatternCircles, PatternWaves } from '@visx/pattern';
import { scaleLinear, scaleOrdinal } from '@visx/scale';
import { transpose } from '@visx/vendor/d3-array';
import { animated, useSpring } from '@react-spring/web';
import useForceUpdate from './useForceUpdate';
import generateData from './generateData';
// constants
const NUM_LAYERS = 20;
const SAMPLES_PER_LAYER = 200;
const BUMPS_PER_LAYER = 10;
export const BACKGROUND = '#ffdede';
// utils
const range = (n: number) => Array.from(new Array(n), (_, i) => i);
const keys = range(NUM_LAYERS);
// scales
const xScale = scaleLinear<number>({
domain: [0, SAMPLES_PER_LAYER - 1],
});
const yScale = scaleLinear<number>({
domain: [-30, 50],
});
const colorScale = scaleOrdinal<number, string>({
domain: keys,
range: ['#ffc409', '#f14702', '#262d97', 'white', '#036ecd', '#9ecadd', '#51666e'],
});
const patternScale = scaleOrdinal<number, string>({
domain: keys,
range: ['mustard', 'cherry', 'navy', 'circles', 'circles', 'circles', 'circles'],
});
// accessors
type Datum = number[];
const getY0 = (d: Datum) => yScale(d[0]) ?? 0;
const getY1 = (d: Datum) => yScale(d[1]) ?? 0;
export type StreamGraphProps = {
width: number;
height: number;
animate?: boolean;
};
export default function Streamgraph({ width, height, animate = true }: StreamGraphProps) {
const forceUpdate = useForceUpdate();
const handlePress = () => forceUpdate();
if (width < 10) return null;
xScale.range([0, width]);
yScale.range([height, 0]);
// generate layers in render to update on touch
const layers = transpose<number>(
keys.map(() => generateData(SAMPLES_PER_LAYER, BUMPS_PER_LAYER)),
);
return (
<svg width={width} height={height}>
<PatternCircles id="mustard" height={40} width={40} radius={5} fill="#036ecf" complement />
<PatternWaves
id="cherry"
height={12}
width={12}
fill="transparent"
stroke="#232493"
strokeWidth={1}
/>
<PatternCircles id="navy" height={60} width={60} radius={10} fill="white" complement />
<PatternCircles
complement
id="circles"
height={60}
width={60}
radius={10}
fill="transparent"
/>
<g onClick={handlePress} onTouchStart={handlePress}>
<rect x={0} y={0} width={width} height={height} fill={BACKGROUND} rx={14} />
<Stack<number[], number>
data={layers}
keys={keys}
offset="wiggle"
color={colorScale}
x={(_, i) => xScale(i) ?? 0}
y0={getY0}
y1={getY1}
>
{({ stacks, path }) =>
stacks.map((stack) => {
// Alternatively use renderprops <Spring to={{ d }}>{tweened => ...}</Spring>
const pathString = path(stack) || '';
const tweened = animate ? useSpring({ pathString }) : { pathString };
const color = colorScale(stack.key);
const pattern = patternScale(stack.key);
return (
<g key={`series-${stack.key}`}>
<animated.path d={tweened.pathString} fill={color} />
<animated.path d={tweened.pathString} fill={`url(#${pattern})`} />
</g>
);
})
}
</Stack>
</g>
</svg>
);
}
Apache Echarts
Apache Echarts 是一个多功能的开源图表库,这应该是大家最常用的图表库了,支持多种图表类型并提供广泛的自定义选项。它使开发人员能够轻松创建具有视觉吸引力的交互式图表,使其成为那些寻求强大而灵活的数据可视化解决方案的人的理想选择。
主要特点
- Apache Echarts 的主要功能包括对各种图表类型的支持、响应式设计和一组丰富的自定义选项。Apache Echarts 支持多种图表类型,包括折线图、条形图、饼图、散点图等,使开发人员能够创建具有视觉吸引力和信息丰富的数据可视化,以满足广泛的项目需求。
- 其响应式设计确保可以在任何设备上轻松查看图表,从而提供跨平台的无缝用户体验。
示例
Apache Echarts 组件可用于创建各种交互式数据可视化,例如:
- line charts 折线图
- pie charts 饼图
- radar charts 雷达图
- bar charts 条形图
- scatter plots 散点图
- heat maps 热图
- tree maps 树状图
- sankey diagrams 桑基图
- box plots 箱形地块
- polar charts 极坐标图
- gauge charts 仪表图
- funnel charts 漏斗图
- word clouds 词云
Nested Pies 嵌套环形图
import * as echarts from 'echarts/core';
import { TooltipComponent, LegendComponent } from 'echarts/components';
import { PieChart } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([
TooltipComponent,
LegendComponent,
PieChart,
CanvasRenderer,
LabelLayout
]);
var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;
option = {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
legend: {
data: [
'Direct',
'Marketing',
'Search Engine',
'Email',
'Union Ads',
'Video Ads',
'Baidu',
'Google',
'Bing',
'Others'
]
},
series: [
{
name: 'Access From',
type: 'pie',
selectedMode: 'single',
radius: [0, '30%'],
label: {
position: 'inner',
fontSize: 14
},
labelLine: {
show: false
},
data: [
{ value: 1548, name: 'Search Engine' },
{ value: 775, name: 'Direct' },
{ value: 679, name: 'Marketing', selected: true }
]
},
{
name: 'Access From',
type: 'pie',
radius: ['45%', '60%'],
labelLine: {
length: 30
},
label: {
formatter: '{a|{a}}{abg|}\n{hr|}\n {b|{b}:}{c} {per|{d}%} ',
backgroundColor: '#F6F8FC',
borderColor: '#8C8D8E',
borderWidth: 1,
borderRadius: 4,
rich: {
a: {
color: '#6E7079',
lineHeight: 22,
align: 'center'
},
hr: {
borderColor: '#8C8D8E',
width: '100%',
borderWidth: 1,
height: 0
},
b: {
color: '#4C5058',
fontSize: 14,
fontWeight: 'bold',
lineHeight: 33
},
per: {
color: '#fff',
backgroundColor: '#4C5058',
padding: [3, 4],
borderRadius: 4
}
}
},
data: [
{ value: 1048, name: 'Baidu' },
{ value: 335, name: 'Direct' },
{ value: 310, name: 'Email' },
{ value: 251, name: 'Google' },
{ value: 234, name: 'Union Ads' },
{ value: 147, name: 'Bing' },
{ value: 135, name: 'Video Ads' },
{ value: 102, name: 'Others' }
]
}
]
};
option && myChart.setOption(option);
Ant Design Charts
蚂蚁设计图表:用户体验至关重要
Ant Design Charts 是一个以用户为中心的 React 图表库,它提供:
- 高质量的默认图表
- 强调用户体验
- 多种图表类型
- 自定义选项
npm install echarts --save
主要特点
- 蚂蚁设计图表的主要功能包括广泛的图表类型、响应式设计和对用户体验的关注。通过提供一整套用于数据可视化的组件,Ant Design Charts 使开发人员能够创建具有视觉吸引力且信息丰富的图表,以满足各种项目要求。
- 它强调用户体验,确保图表易于理解和交互,为最终用户提供无缝体验。
示例
Ant Design Charts 组件可用于创建各种数据可视化,例如:
- line charts 折线图
- bar charts 条形图
- pie charts 饼图
- area charts 面积图
- scatter charts 散点图
- radar charts 雷达图
- funnel charts 漏斗图
- gauge charts 仪表图
- heatmap charts 热图图表
- treemap charts 树状图
- waterfall charts 瀑布图
词云图
import { WordCloud } from '@ant-design/plots';
import React from 'react';
import ReactDOM from 'react-dom';
const DemoWordCloud = () => {
const config = {
paddingTop: 40,
data: {
type: 'fetch',
value: 'https://assets.antv.antgroup.com/g2/philosophy-word.json',
},
layout: { spiral: 'rectangular' },
colorField: 'text',
};
return <WordCloud {...config} />;
};
ReactDOM.render(<DemoWordCloud />, document.getElementById('container'));
选择正确的 React 图表库的技巧
在为您的项目选择 React 图表库时,您应该权衡项目规范、适应性选项和库的用户友好性等方面。每个库都有其优点和缺点,最佳选择将取决于您项目的具体需求,您可以选择正确的 React 图表库来创建引人入胜且信息丰富的图表,从而增强用户体验并推动数据驱动的决策。 大家平时都是用什么图表,欢迎评论区留言!
❤今天的分享就到这里,希望可以帮助到你!假如你对文章感兴趣,可以来我的公众号:小新学研社。