Skip to content

Multiple Axes #372

Open
Open
@JerryPan2718

Description

@JerryPan2718
Screenshot 2024-06-05 at 10 54 25 AM Screenshot 2024-06-05 at 10 57 37 AM

We want to show 2 metric values with their respective left and right y-axes, but we values cannot be assigned to either left or right y-axis by our code.

import ResizableBox from "../ResizableBox";
import useDemoConfig from "../useDemoConfig";
import React from "react";
import { AxisOptions, Chart } from "react-charts";

export default function MultipleAxes() {
  const { data, randomizeData } = useDemoConfig({
    series: 4,
    dataType: "ordinal",
  });
  data[1].data = data[1].data.map((item) => ({
    ...item,
    secondary: item.secondary * 0.01,
  }));

  console.log({ data });

  // @ts-ignore
  data.forEach((d, i) => (d.secondaryAxisId = i >= 1 ? "2" : undefined));

  const primaryAxis = React.useMemo<
    AxisOptions<(typeof data)[number]["data"][number]>
  >(
    () => ({
      getValue: (datum) => datum.primary,
      // Pad the automatically detected time scale with half of the band-size
      padBandRange: true,
    }),
    []
  );

  const secondaryAxes = React.useMemo<
    AxisOptions<(typeof data)[number]["data"][number]>[]
  >(
    () => [
      {
        getValue: (datum) => datum.secondary,
        elementType: "bar",
        // stacked: true,
      },
      {
        id: "2",
        getValue: (datum) => datum.secondary * 0.01,
        elementType: "bar",
      },
    ],
    []
  );

  return (
    <>
      <button onClick={randomizeData}>Randomize Data</button>
      <br />
      <br />
      <ResizableBox>
        <Chart
          options={{
            data,
            primaryAxis,
            secondaryAxes,
          }}
        />
      </ResizableBox>
    </>
  );
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions