recharts 實踐

assassin_cike發表於2024-11-18

1. 柱狀圖橫座標根據時間不均勻分佈

一般chart橫座標之間的刻度間隔都是均勻的,但是我的需求是根據日期時間顯示對應的資料。

const TaskBarChat = ({ data }: IProps) => {
  return Object.entries(data).map(([key, val]) => {
    const data = val.map((x) => ({
      ...x,
      now: dayjs(x.now).valueOf(),
    }));
    const firstItem = data[0];
    const lastItem = data[data.length - 1];

    const domain = [firstItem.now, lastItem.now];

    return (
      <Flex key={key} className={styles.taskBar} vertical>
        <div className="flex gap-8">
          <b className={styles.taskBarTitle}>ID: {key}</b>
          <b className={styles.taskBarTitle}>Lag: {lastItem.lag}</b>
          <b className={styles.taskBarTitle}>Pending: {lastItem.pending}</b>
        </div>
        <ResponsiveContainer>
          <BarChart data={data}>
            <XAxis
              dataKey="now"
              type="number"
              scale={'time'}
              domain={domain}
              tickFormatter={(x) => formatTime(x)}
              allowDataOverflow
              angle={60}
              padding={{ left: 20, right: 20 }}
              tickMargin={20}
            />
            <CartesianGrid strokeDasharray="3 3" />
            <Tooltip
              wrapperStyle={{ pointerEvents: 'auto' }}
              content={<CustomTooltip></CustomTooltip>}
              trigger="click"
            />
            <Legend wrapperStyle={{ bottom: -22 }} />
            <Bar
              dataKey="done"
              fill="#2fe235"
              activeBar={<Rectangle fill="pink" stroke="blue" />}
            />
            <Bar
              dataKey="failed"
              fill="#ef3b74"
              activeBar={<Rectangle fill="gold" stroke="purple" />}
            />
          </BarChart>
        </ResponsiveContainer>
        <Divider></Divider>
      </Flex>
    );
  });
};

export default TaskBarChat;

參考:recharts-area-chart-with-date-axis

2. 讓tooltip內容可選擇

            <Tooltip
              wrapperStyle={{ pointerEvents: 'auto' }}
              content={<CustomTooltip></CustomTooltip>}
              trigger="click"
            />

參考:
How to make recharts custom tooltip to be clickable?
How to make clickable tooltip? #1640

相關文章