Nivo Line Chart页面缩放时出现transform属性错误求助
Nivo折线图缩放时SVG Transform错误的修复方案
问题本质
你遇到的Error: <g> attribute transform: Expected ')'错误,是因为SVG渲染时生成了无效的transform属性值(比如空的translate参数),根源是Nivo在响应式缩放场景下,堆叠模式的y轴计算出现了精度异常(比如产生极小的浮点数),导致点或线条的坐标渲染失败。
你的代码问题点
你在yScale中设置了stacked: true(堆叠模式),同时启用了数据点的渲染配置(pointSize、pointBorderWidth等)。堆叠模式下的坐标计算逻辑在页面缩放时,容易触发数值精度问题,进而生成无效的SVG属性。
修复方法(任选其一即可)
方法1:关闭堆叠模式(推荐,若业务不需要堆叠)
如果你的折线图不需要堆叠效果,直接将yScale中的stacked改为false:
yScale={{ type: "linear", min: "auto", max: "auto", stacked: false, // 改为false reverse: false, }}
方法2:禁用数据点渲染
若不需要显示折线图上的数据点,移除或禁用所有point相关配置:
// 移除以下配置,或者设置pointSize: 0 pointSize: 0, // pointColor={{ theme: "background" }} // pointBorderWidth: 2 // pointBorderColor={{ from: "serieColor" }} // pointLabelYOffset: -12
方法3:手动指定y轴范围,避免精度异常
通过手动设置yScale的min和max,强制Nivo使用整数范围,避免极小浮点数的产生:
yScale={{ type: "linear", min: 0, // 根据你的数据设置合理最小值 max: 100, // 根据你的数据设置合理最大值 stacked: true, reverse: false, }}
方法4:升级Nivo版本
如果是旧版本Nivo的bug,升级到最新版@nivo/line:
npm update @nivo/line # 或 yarn upgrade @nivo/line
修改后的完整代码示例(方法1)
import { ResponsiveLine } from "@nivo/line"; import { useTheme } from "@mui/material"; import { tokens } from "../theme"; import { mockLineData as data } from "../data/mockLineData"; const LineChart = () => { const theme = useTheme(); const colors = tokens(theme.palette.mode); return ( <ResponsiveLine data={data} theme={{ axis: { domain: { line: { stroke: colors.grey[100], }, }, legend: { text: { fill: colors.grey[100], }, }, ticks: { line: { stroke: colors.grey[100], strokeWidth: 1, }, text: { fill: colors.grey[100], }, }, }, legends: { text: { fill: colors.grey[100], }, }, tooltip: { container: { color: colors.primary[500], }, }, }} colors={{ scheme: "nivo" }} margin={{ top: 50, right: 110, bottom: 50, left: 60 }} xScale={{ type: "point" }} yScale={{ type: "linear", min: "auto", max: "auto", stacked: false, // 核心修改:关闭堆叠 reverse: false, }} yFormat=" >-.2f" curve="catmullRom" axisTop={null} axisRight={null} axisBottom={{ orient: "bottom", tickSize: 0, tickPadding: 5, tickRotation: 0, legend: "transportation", legendOffset: 36, legendPosition: "middle", }} axisLeft={{ orient: "left", tickValues: 5, tickSize: 3, tickPadding: 5, tickRotation: 0, legend: "count", legendOffset: -40, legendPosition: "middle", }} enableGridX={false} enableGridY={false} pointSize={8} pointColor={{ theme: "background" }} pointBorderWidth={2} pointBorderColor={{ from: "serieColor" }} pointLabelYOffset={-12} useMesh={true} legends={[ { anchor: "bottom-right", direction: "column", justify: false, translateX: 100, translateY: 0, itemsSpacing: 0, itemDirection: "left-to-right", itemWidth: 80, itemHeight: 20, itemOpacity: 0.75, symbolSize: 12, symbolShape: "circle", symbolBorderColor: "rgba(0, 0, 0, .5)", effects: [ { on: "hover", style: { itemBackground: "rgba(0, 0, 0, .03)", itemOpacity: 1, }, }, ], }, ]} /> ); }; export default LineChart;
内容的提问来源于stack exchange,提问作者alexsmt
相关产品推荐
相关产品推荐

