You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中@rainbow-me/animated-charts图表路径最值位置标记方法

在@rainbow-me/animated-charts中标记图表路径的峰值和最小值

我正在使用@rainbow-me/animated-charts库绘制图表,想知道如何在图表路径上标记峰值和最小值。以下是我的相关代码及图表截图:

<ChartPathProvider
  data={{
    points: monotoneCubicInterpolation({
      data,
      range: 40,
    }),
    smoothingStrategy: "bezier",
  }}
>
  <View>
    <ChartPath
      height={moderateScale(280)}
      stroke={COLORS.greenChart}
      strokeWidth={3}
      width={screenWidth}
    />
  </View>
</ChartPathProvider>

简易图表


实现方法

1. 先定位数据中的极值点

在处理插值前,先遍历原始data数组,找出峰值(最大值)和最小值对应的点:

// 从原始数据中筛选峰值和最小值点
let peakPoint = data[0];
let minPoint = data[0];
data.forEach(point => {
  if (point.y > peakPoint.y) peakPoint = point;
  if (point.y < minPoint.y) minPoint = point;
});

2. 用ChartPoint组件标记极值

利用库提供的ChartPoint组件和useChartPathContext钩子,将极值点映射到图表容器的坐标上,实现自定义标记:

import { ChartPathProvider, ChartPath, useChartPathContext } from '@rainbow-me/animated-charts';

// 自定义极值标记组件
const ExtremumMarker = ({ point, color, label }) => {
  const { chartBounds, getPointPosition } = useChartPathContext();
  // 将数据点转换为图表内的绝对坐标
  const { x, y } = getPointPosition(point, chartBounds);

  return (
    <View style={{ position: 'absolute', left: x, top: y }}>
      {/* 标记圆点 */}
      <View style={{
        width: 8,
        height: 8,
        borderRadius: 4,
        backgroundColor: color,
        borderWidth: 2,
        borderColor: '#ffffff',
      }} />
      {/* 可选:添加数值标签 */}
      <Text style={{
        position: 'absolute',
        top: -22,
        left: -18,
        color: color,
        fontSize: 12,
        fontWeight: '600',
      }}>{label}</Text>
    </View>
  );
};

// 渲染图表部分
<ChartPathProvider
  data={{
    points: monotoneCubicInterpolation({
      data,
      range: 40,
    }),
    smoothingStrategy: "bezier",
  }}
>
  <View>
    <ChartPath
      height={moderateScale(280)}
      stroke={COLORS.greenChart}
      strokeWidth={3}
      width={screenWidth}
    />
    {/* 标记峰值 */}
    <ExtremumMarker point={peakPoint} color="#ff3b30" label={`峰值: ${peakPoint.y}`} />
    {/* 标记最小值 */}
    <ExtremumMarker point={minPoint} color="#007aff" label={`最小值: ${minPoint.y}`} />
  </View>
</ChartPathProvider>

关键说明

  • useChartPathContext钩子提供了图表边界信息和坐标转换方法getPointPosition,能自动适配图表的缩放、偏移逻辑。
  • 自定义标记组件可以灵活调整样式,比如圆点大小、标签位置、颜色等,适配不同UI需求。
  • 如果需要基于插值后的points数组找极值,逻辑和处理原始数据一致,直接遍历points数组即可。

内容的提问来源于stack exchange,提问作者Manish Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:06:29