PAYATHON 2026

React Native 如何在 categorical axis 上绘制无伪尾线的历史与预测?

排障赵师傅

结论

按日期顺序建立共享 x 轴,再分别生成历史和预测的绘制路径。两个系列无需补齐长度,也不用填入 0、null 或 NaN。

对于约 30 个历史点和 14 个预测点,直接使用 react-native-svg 比较合适。坐标计算简单,也方便控制每条路径的起点和终点。

要连接两段线,可以把最后一个历史点作为预测路径的起点:

历史路径:…… → (03-25, 44) → (03-26, 34)
预测路径:                   (03-26, 34) → (03-27, 36) → ……

这里只复用已有历史点的坐标,不增加日期标签,也不修改预测数据。连接线段使用预测线的颜色。

为什么填充值解决不了问题

0 是有效价格,图表会将它纳入坐标范围,并绘制相应线段。设置 fromZero={false} 也不会隐藏这些点。

NaN 不是有效的绘图坐标,进入 SVG 路径后可能导致 d 属性无效。具体如何报错,取决于图表库、SVG 实现和运行平台。

用 null 表示断点,需要绘图层明确支持。普通折线、Bezier 曲线、圆点和面积填充可能各有处理逻辑,某个模式接受 null,不代表整张图都支持缺失值。

下面的类型断言也无法解决这个问题:

historySeries as number[]

它只改变 TypeScript 的类型判断,不会把数组中的 null 或 NaN 转换为有效数值。

先确定共享坐标和边界规则

将排序后的日期映射为索引:

日期:2026-02-27  2026-02-28  2026-03-01  ……  2026-04-09
索引:     0           1           2     ……      N - 1

第 i 个点的横坐标为:

x(i) = left + i / (N - 1) × plotWidth

日期只用于排序、标签和提示信息,不用于计算时间间隔。按索引映射后,就能得到 categorical axis 所需的等距效果。

两个系列还必须共用同一套 y 轴映射,取值范围由全部历史值和预测值共同确定。否则,即使把两张图叠在一起,相同价格也可能落在不同高度。

最后一个历史点和第一个预测点通常有不同的日期和价格,需要在两点之间画一段线才能连续显示。这段连接线归入预测路径。

使用 react-native-svg 绘制

先在项目中安装并配置 react-native-svg。下面的组件使用直线段绘制,包含共享坐标轴、网格、日期标签和数据点。

输入日期应统一为 YYYY-MM-DD 格式,所有预测日期都必须晚于最后一个历史日期。

import React from 'react';
import { Text, View } from 'react-native';
import Svg, {
  Circle,
  Line,
  Path,
  Text as SvgText,
} from 'react-native-svg';

type Prices = Record<string, number>;

type Point = {
  date: string;
  index: number;
  value: number;
};

type Props = {
  history: Prices;
  forecast: Prices;
  width: number;
  height?: number;
};

const HISTORY_COLOR = '#36a2eb';
const FORECAST_COLOR = '#ff9f40';

export function HistoryForecastChart({
  history,
  forecast,
  width,
  height = 260,
}: Props) {
  const historyDates = Object.keys(history).sort();
  const forecastDates = Object.keys(forecast).sort();

  const allDates = [
    ...new Set([...historyDates, ...forecastDates]),
  ].sort();

  if (allDates.length === 0) {
    return <Text>暂无数据</Text>;
  }

  const values = [
    ...Object.values(history),
    ...Object.values(forecast),
  ];

  if (values.some((value) => !Number.isFinite(value))) {
    throw new Error('价格必须是有限数值');
  }

  if (
    historyDates.length > 0 &&
    forecastDates.length > 0 &&
    forecastDates[0] <= historyDates[historyDates.length - 1]
  ) {
    throw new Error('预测日期必须晚于最后一个历史日期');
  }

  const left = 52;
  const right = 20;
  const top = 16;
  const bottom = 36;

  const plotWidth = width - left - right;
  const plotHeight = height - top - bottom;

  if (
    !Number.isFinite(plotWidth) ||
    !Number.isFinite(plotHeight) ||
    plotWidth <= 0 ||
    plotHeight <= 0
  ) {
    return null;
  }

  const indexByDate = new Map(
    allDates.map((date, index) => [date, index])
  );

  const toPoints = (dates: string[], prices: Prices): Point[] =>
    dates.map((date) => ({
      date,
      index: indexByDate.get(date)!,
      value: prices[date],
    }));

  const historyPoints = toPoints(historyDates, history);
  const forecastPoints = toPoints(forecastDates, forecast);

  const lastHistory =
    historyPoints[historyPoints.length - 1];

  // 只为路径加入连接锚点,不修改 forecast 数据。
  const forecastPathPoints =
    lastHistory && forecastPoints.length > 0
      ? [lastHistory, ...forecastPoints]
      : forecastPoints;

  const minValue = Math.min(...values);
  const maxValue = Math.max(...values);

  // 所有价格相同时,也保留非零的 y 轴范围。
  const yPadding =
    maxValue > minValue
      ? (maxValue - minValue) * 0.1
      : Math.max(Math.abs(minValue) * 0.05, 1);

  const yMin = minValue - yPadding;
  const yMax = maxValue + yPadding;

  const x = (index: number) =>
    allDates.length === 1
      ? left + plotWidth / 2
      : left + (index / (allDates.length - 1)) * plotWidth;

  const y = (value: number) =>
    top + ((yMax - value) / (yMax - yMin)) * plotHeight;

  const makePath = (points: Point[]) =>
    points
      .map(
        (point, index) =>
          `${index === 0 ? 'M' : 'L'} ` +
          `${x(point.index)} ${y(point.value)}`
      )
      .join(' ');

  const ticks = Array.from(
    { length: 5 },
    (_, index) => yMin + ((yMax - yMin) * index) / 4
  );

  const labelIndices = [
    ...new Set([
      0,
      Math.floor((allDates.length - 1) / 2),
      allDates.length - 1,
    ]),
  ];

  return (
    <View>
      <Svg width={width} height={height}>
        {ticks.map((value, index) => (
          <React.Fragment key={index}>
            <Line
              x1={left}
              y1={y(value)}
              x2={width - right}
              y2={y(value)}
              stroke="#ddd"
              strokeDasharray="4 4"
            />
            <SvgText
              x={left - 8}
              y={y(value) + 4}
              textAnchor="end"
              fontSize={11}
              fill="#555"
            >
              {Number(value.toFixed(2))}
            </SvgText>
          </React.Fragment>
        ))}

        <Line
          x1={left}
          y1={top + plotHeight}
          x2={width - right}
          y2={top + plotHeight}
          stroke="#aaa"
        />

        {labelIndices.map((index) => (
          <SvgText
            key={allDates[index]}
            x={x(index)}
            y={height - 10}
            textAnchor={
              allDates.length === 1
                ? 'middle'
                : index === 0
                  ? 'start'
                  : index === allDates.length - 1
                    ? 'end'
                    : 'middle'
            }
            fontSize={11}
            fill="#444"
          >
            {allDates[index].slice(5)}
          </SvgText>
        ))}

        {historyPoints.length > 0 && (
          <Path
            d={makePath(historyPoints)}
            fill="none"
            stroke={HISTORY_COLOR}
            strokeWidth={3}
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        )}

        {forecastPathPoints.length > 0 && (
          <Path
            d={makePath(forecastPathPoints)}
            fill="none"
            stroke={FORECAST_COLOR}
            strokeWidth={3}
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        )}

        {historyPoints.map((point) => (
          <Circle
            key={`history-${point.date}`}
            cx={x(point.index)}
            cy={y(point.value)}
            r={3}
            fill={HISTORY_COLOR}
          />
        ))}

        {forecastPoints.map((point) => (
          <Circle
            key={`forecast-${point.date}`}
            cx={x(point.index)}
            cy={y(point.value)}
            r={3}
            fill={FORECAST_COLOR}
          />
        ))}
      </Svg>

      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'center',
        }}
      >
        <Text style={{ color: HISTORY_COLOR, marginRight: 20 }}>
          历史价格
        </Text>
        <Text style={{ color: FORECAST_COLOR }}>
          预测价格
        </Text>
      </View>
    </View>
  );
}

保留问题中的 history 和 forecast 对象,在页面中使用:

import React from 'react';
import {
  SafeAreaView,
  useWindowDimensions,
  View,
} from 'react-native';
import { HistoryForecastChart } from './HistoryForecastChart';

export default function App() {
  const { width } = useWindowDimensions();

  return (
    <SafeAreaView
      style={{
        flex: 1,
        backgroundColor: '#fff',
        justifyContent: 'center',
      }}
    >
      <View style={{ paddingHorizontal: 16 }}>
        <HistoryForecastChart
          history={history}
          forecast={forecast}
          width={width - 32}
        />
      </View>
    </SafeAreaView>
  );
}

如果图表放在卡片、侧栏等宽度受限的容器中,应通过容器的 onLayout 获取实际宽度,再传给组件。

历史路径只包含历史点,预测路径则包含最后一个历史点和全部预测点。两条路径共用 x()、y(),不使用占位点,因此不会出现填充值造成的尾线。

继续使用 react-native-chart-kit,有没有简洁变通?

对于题目中已经出现的问题,不建议继续尝试其他填充值,关闭 bezier 也不能作为通用修复。

仅把两个 dataset 改成不同长度仍不够。预测数组需要知道自己在共享轴上的起始位置,否则可能从左侧开始绘制,或采用与历史系列不同的横向分布。

保留 react-native-chart-kit 时,可以考虑两种做法:

  • 保留坐标轴和网格,通过所用版本提供的自定义绘制入口,例如 decorator,绘制两条 SVG 路径。需要核对该版本的绘图区边距和坐标映射,避免路径与标签错位。
  • 修改或维护一份绘线实现,让它接受带有全局索引的点,并在指定范围内生成路径。圆点和面积填充也要同步处理。

两种做法都需要接管部分绘制逻辑。对于当前规模的图表,直接使用上面的 SVG 组件通常更容易维护。

也不建议直接叠放两张各自自动缩放的 LineChart。要让它们准确连接,除了组件宽高,还需要统一绘图区、x 轴范围、y 轴范围和边距。

Victory 和 react-native-svg-charts 如何选择?

选择其他图表库时,需要确认每条线能否使用独立的点数组,同时共用坐标范围。

方案实现要点
victory-native使用全局索引作为 x 值,在共享坐标系中分别绘制历史和预测。API 需按安装版本确认,旧版 VictoryChart / VictoryLine 示例不能直接套用到采用 CartesianChart 的版本。
react-native-svg-charts可使用对象数据、x 访问器和共享 domain 实现;需核对所用版本的访问器、范围设置及多系列绘制方式。
react-native-svg自己计算共享坐标,分别绘制独立的 Path,适合当前数据量和明确的分段需求。

即使库中将横轴称为 numeric axis,也可以用 0、1、2…… 作为 x 值,再将刻度格式化为日期。使用全局索引后,视觉上就能得到所需的等距日期轴。

实现时还要注意什么?

排序时应使用完整日期。统一的 YYYY-MM-DD 字符串可以直接按字典序排序,05-29 或“5 月 29 日”则无法正确表达跨年顺序。

如果需要平滑曲线,应分别为历史点和“历史锚点加预测点”生成曲线路径。分别插值可以保证两段在位置上相连,但边界斜率未必一致。绘制价格图时,还要检查插值是否产生超出相邻数据值的波峰或波谷。

共享锚点不要重复计入业务数据。14 个预测值对应的绘制路径可以有 15 个点,其中额外的一个点只用于连接。计算预测统计或展示 tooltip 时,仍需区分历史点和预测点。

等距横轴表达的是观测顺序。历史数据中,相隔一天和相隔数周的两个点会有相同的间距。因此,页面应明确标注“按观测点等距排列”,并在详情中显示完整日期。

备注:内容仅供参考。