3

Does anyone know if the below scenario with the weeks axis is possible in recharts?

Let's say for example, there is a days graph. There are about 20 consecutive days in the X Axis. You need an additional X Axis below that mentions the week #, but the week should float in the middle of the range of it's associated days, like below:

    Mon Tue Wed Thr Fri Sat Sun Mon Tue Wed Thr Fri Sat Sun Mon Tue Wed Thr Fri Sat

               Week 1                      Week 2                   Week 3

Edit: I think this is possible if we create a custom function for the axis and add a couple of conditions for the placement of the week# to be precisely under a certain area.

Thank you for the comments and research! My requirements have changed so I did not go further into this issue.

1 Answer 1

11

It's absolutely possible to have many XAxis on your graph. For this, you need to add an <XAxis /> line to your graph, and set its xAxisId to a unique value, so that the graph can differentiate the different XAxis. (NB: all XAxis will need a different xAxisId; its default value being set to 0, you'll need to override this default value).

Then, to have a general XAxis data without any repetitions, you'll need the allowDuplicatedCategory prop on the XAxis set to false. However, the first and last tick will not be centered. I'll see if I can find a solution for this.

With your given data example, the resulted graph could look like this:

import React from "react";

import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend
} from "recharts";

const data = [
  { name: "Mon", uv: 4000, pv: 2400, amt: 2400, week: "Week 1" },
  { name: "Tue", uv: 3000, pv: 1398, amt: 2210, week: "Week 1" },
  { name: "Wed", uv: 2000, pv: 9800, amt: 2290, week: "Week 1" },
  { name: "Thu", uv: 2780, pv: 3908, amt: 2000, week: "Week 1" },
  { name: "Fri", uv: 1890, pv: 4800, amt: 2181, week: "Week 1" },
  { name: "Sat", uv: 2390, pv: 3800, amt: 2500, week: "Week 1" },
  { name: "Sun", uv: 3490, pv: 4300, amt: 2100, week: "Week 1" },
  ...
];

const SimpleLineChart = () => {
  return (
    <LineChart
      width={1200}
      height={300}
      data={data}
      margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
    >
      <XAxis xAxisId="0" dataKey="name" />
      <XAxis xAxisId="1" dataKey="week" allowDuplicatedCategory={false} />
      <YAxis />
      <CartesianGrid strokeDasharray="3 3" />
      <Tooltip />
      <Legend />
      <Line
        type="monotone"
        dataKey="pv"
        stroke="#8884d8"
        activeDot={{ r: 8 }}
      />
      <Line type="monotone" dataKey="uv" stroke="#82ca9d" />
    </LineChart>
  );
};

export default SimpleLineChart;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.