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

如何在React JS项目中实现Google风格股票图表(每日时序数据)

在React项目中实现Google风格股票图表方案

一、选用适配的图表库

直接使用react-google-charts——它是Google Charts的React官方封装库,能完美还原Google风格的图表视觉效果。

安装命令:

npm install react-google-charts
# 或使用yarn
yarn add react-google-charts

二、数据预处理

先筛选出一个月前至今的有效数据,同时把时间戳转换为Google Charts可识别的日期格式:

// 计算一个月前的毫秒级时间戳
const oneMonthAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;

// 过滤数据并转换格式
const processedData = exampleData
  .filter(([timestamp]) => timestamp >= oneMonthAgo)
  .map(([timestamp, price]) => [new Date(timestamp), price]);

// 补充表头(Google Charts要求首行为列名)
const chartData = [['日期', '价格'], ...processedData];

注:你的原始数据格式应为[[时间戳, 价格], [时间戳, 价格]],而非大括号包裹的结构

三、编写React图表组件

通过Chart组件配置折线图,调整参数贴近Google的简洁风格:

import React from 'react';
import { Chart } from 'react-google-charts';

const StockChart = ({ rawData }) => {
  // 数据预处理逻辑
  const oneMonthAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;
  const processedData = rawData
    .filter(([timestamp]) => timestamp >= oneMonthAgo)
    .map(([timestamp, price]) => [new Date(timestamp), price]);
  const chartData = [['日期', '价格'], ...processedData];

  // Google风格图表配置
  const options = {
    title: '股票价格走势',
    curveType: 'function', // 平滑曲线,贴合Google视觉风格
    legend: { position: 'bottom' },
    hAxis: {
      format: 'MM-dd', // 日期显示格式
      gridlines: { count: 5 }, // 减少网格线,保持简洁
    },
    vAxis: {
      format: '$#,###', // 价格格式化显示
      gridlines: { count: 4 },
    },
    backgroundColor: 'transparent',
    colors: ['#1a73e8'], // 使用Google标志性蓝色
    lineWidth: 2,
  };

  return (
    <Chart
      chartType="LineChart"
      width="100%"
      height="400px"
      data={chartData}
      options={options}
    />
  );
};

export default StockChart;

四、组件调用示例

在父组件中传入你的原始数据即可渲染图表:

import StockChart from './StockChart';

// 你的原始每日数据示例
const exampleData = [
  [1698844800000, 125.5],
  [1698931200000, 126.2],
  [1699017600000, 124.8],
  // ...更多历史数据
];

function App() {
  return (
    <div className="App">
      <StockChart rawData={exampleData} />
    </div>
  );
}

export default App;

五、进阶样式优化(可选)

如果要更贴近Google Finance的视觉效果,可调整以下配置:

  • 隐藏网格线:gridlines: { color: 'transparent' }
  • 增强工具提示:tooltip: { isHtml: true }
  • 调整标题样式:titleTextStyle: { fontSize: 16, color: '#202124' }

内容的提问来源于stack exchange,提问作者Kamlesh Gorasiya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:20:37