Harmo-Ron Kallaste
Harmo-Ron Kallaste

Reputation: 1

How to assign specific values for different bars in <BarChart>

I need to create a <BarChart> with mui-x.

Here is some sample data that I am working with:

const correctDate = "21.05.2003";

const rawDates = [
  "21.05.2003",
  "21.05.2005",
  null,
  "27.05.2003",
  "21.05.2003",
  null,
  "21.05.2005",
];

I would want to color the bars like this:

Date Count Color
21.05.2003 2 Green
21.05.2005 2 Yellow
27.05.2003 1 Yellow
Missing date 2 Red

Ideally the colors would come from a theme:

import { createTheme } from "@mui/material/styles";
import { green, red, yellow } from '@mui/material/colors';

const realTimeTheme = createTheme(
    {
        palette: {
            success: {
                main: green['A200'],
                light: green['A700']
            },
            error: {
                main: red[500],
                light: red[700]
            },
            warning: {
                main: yellow[300],
                light: yellow[500],
            },
        },
    },
);

export default realTimeTheme;

Can someone provide some insight on how to achieve something like this?

Upvotes: 0

Views: 20

Answers (1)

Łukasz Daniel Mastalerz
Łukasz Daniel Mastalerz

Reputation: 2217

Try something like this (if I understood you in proper way...)

import { BarChart } from "@mui/x-charts/BarChart";
import { createTheme } from "@mui/material/styles";
import { green, red, yellow } from "@mui/material/colors";

const realTimeTheme = createTheme({
  palette: {
    success: { main: green["A200"], light: green["A700"] },
    error: { main: red[500], light: red[700] },
    warning: { main: yellow[300], light: yellow[500] },
  },
});

export default function MyBarChart() {
  const aggregatedData = [
    { date: "21.05.2003", count: 2 },
    { date: "21.05.2005", count: 2 },
    { date: "27.05.2003", count: 1 },
    { date: "Missing date", count: 2 },
  ];

  const dates = aggregatedData.map((item) => item.date);
  const counts = aggregatedData.map((item) => item.count);

  const barColors = [
    realTimeTheme.palette.success.main, // for 21.05.2003
    realTimeTheme.palette.warning.main, // for 21.05.2005
    realTimeTheme.palette.warning.main, // for 27.05.2003
    realTimeTheme.palette.error.main, // for Missing date
  ];

  return (
    <BarChart
      width={500}
      height={300}
      series={[{ data: counts, id: "dateCount" }]}
      xAxis={[
        {
          scaleType: "band",
          data: dates,
          colorMap: {
            type: "ordinal",
            values: dates,
            colors: barColors,
          },
        },
      ]}
    />
  );
}

CODESANDBOX

Upvotes: 0

Related Questions