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

如何使用React-chartjs-2实现过去5年已发布产品的时间轴柱状图

实现基于React-ChartJS-2的已发布产品时间轴柱状图

我来帮你搞定这个需求!其实核心就是把products数组里的每个元素和对应的年份标签绑定,统计每个年份的已发布产品状态,再把数据适配到ChartJS的格式里就行。下面是完整的实现方案:

核心逻辑梳理

  • products数组的索引和labels数组的索引完全对应:products[0]对应2018年,products[1]对应2019年,以此类推到products[4]对应2022年
  • 我们需要为每个年份生成对应的数据:如果该年份的产品状态是released,则标记为可高亮的有效数据,否则显示为低透明度的占位,这样既能保留所有年份标签,又能突出已发布的产品

修改后的完整代码

import React from "react";
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend } from "chart.js";
import { Bar } from "react-chartjs-2";

// 注册ChartJS所需的核心组件
ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

// 图表配置项
export const options = {
  responsive: true,
  plugins: {
    legend: {
      position: "top" as const
    },
    title: {
      display: true,
      text: "过去5年已发布产品时间轴" // 修改为贴合需求的标题
    },
    tooltip: {
      // 自定义tooltip内容,直观展示年份和产品状态
      callbacks: {
        label: function(context) {
          const year = context.label;
          const status = products[context.dataIndex].status;
          return status === "released" ? `${year}: 已发布` : `${year}: 开发中`;
        }
      }
    }
  },
  scales: {
    y: {
      beginAtZero: true,
      ticks: {
        stepSize: 1 // y轴只显示整数,符合产品数量的特性
      }
    }
  }
};

// 原始产品数据
const products = [
  { id: 1, status: "released" },
  { id: 2, status: "in progress" },
  { id: 3, status: "in progress" },
  { id: 4, status: "released" },
  { id: 5, status: "released" }
];

// 年份标签数组
const labels = ["2018", "2019", "2020", "2021", "2022"];

// 处理图表数据:绑定年份标签与产品状态
export const data = {
  labels,
  datasets: [
    {
      label: "产品发布状态",
      // 转换产品状态为图表可识别的数值:已发布为1,开发中为0
      data: products.map(product => product.status === "released" ? 1 : 0),
      // 为不同状态的柱子设置差异化样式,实现高亮效果
      backgroundColor: products.map(product => 
        product.status === "released" ? "rgba(53, 162, 235, 0.7)" : "rgba(200, 200, 200, 0.3)"
      ),
      borderColor: products.map(product => 
        product.status === "released" ? "rgba(53, 162, 235, 1)" : "rgba(200, 200, 200, 1)"
      ),
      borderWidth: 1
    }
  ]
};

export function App() {
  return <Bar options={options} data={data} />;
}

关键修改点说明

  1. 数据适配:

    • 用products.map替代了faker的模拟数据,直接根据每个产品的status生成对应年份的数值(1代表已发布,0代表开发中)
    • 为不同状态的柱子设置了差异化的颜色,已发布的柱子用高亮的蓝色,开发中的用浅灰色占位,完美实现“仅高亮已发布产品”的需求
  2. 图表体验优化:

    • 修改了标题为更贴合业务的文字
    • 自定义了tooltip内容,鼠标悬停时能直接看到对应年份的产品状态
    • 配置y轴从0开始且步长为1,符合产品数量的整数特性,避免图表显示异常
  3. 标签绑定:

    • 利用products和labels的索引一一对应关系,确保每个年份标签都能匹配到正确的产品数据,所有年份标签都会正常显示在图表上

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:17:46