javascriptreactjsdeploymentmui-x-charts

React MUI BarChart Colorizing


I want to create a bar chart where each category (e.g., "Oral Ambalaj", "Onkolotik", etc.) has a single value. Each category should be displayed in a different color, and all categories should be shown on the same y-axis. Here some pic. to i want enter image description here

enter image description here

i wana splite my color and data like first image but i didnt.

import { BarChart } from '@mui/x-charts/BarChart';
import { BarSeriesType } from '@mui/x-charts/models';

const data = [2, 5, 3, 6, 8, 11, 8];
const categories = [
"Oral Ambalaj",
"Onkolotik",
"Görsel Kontrol",
"Oral Üretim",
"Steril Ambalaj",
"Steril Üretim",
"Diğer"
];
const colors = ['#FF5733', '#33FF57', '#3357FF', '#FF33A1', '#FF8F33', '#33FFF5', '#B833FF'];

// Series Tanımlaması
const series: BarSeriesType[] = categories.map((category, index) => ({
type: 'bar',
data: [data[index]],
color: colors[index % colors.length],
//label: categories[index],
}));

function CustomBarChart() {
return (
    <BarChart
    xAxis={[
        {
        id: "barCategories",
        data: categories,
        scaleType: "band",
        },
    ]}
    series={series}
    width={800}
    height={300}
    barLabel="value"
    />
);
}

export default CustomBarChart;

Here is my code. Thank you very much in advance.


Solution

  • You can use the axis[].colorMap for that instead. You also need to use a single series, instead of the multiple ones you are using.

    import * as React from 'react';
    import { BarChart } from '@mui/x-charts/BarChart';
    import { BarSeriesType } from '@mui/x-charts/models';
    
    const data = [2, 5, 3, 6, 8, 11, 8];
    const categories = [
      'Oral Ambalaj',
      'Onkolotik',
      'Görsel Kontrol',
      'Oral Üretim',
      'Steril Ambalaj',
      'Steril Üretim',
      'Diğer',
    ];
    const colors = [
      '#FF5733',
      '#33FF57',
      '#3357FF',
      '#FF33A1',
      '#FF8F33',
      '#33FFF5',
      '#B833FF',
    ];
    
    const series: BarSeriesType[] = [
      {
        type: 'bar',
        data,
      },
    ];
    
    function CustomBarChart() {
      return (
        <BarChart
          xAxis={[
            {
              id: 'barCategories',
              data: categories,
              scaleType: 'band',
              colorMap: {
                type: 'ordinal',
                colors,
              },
            },
          ]}
          series={series}
          width={800}
          height={300}
          barLabel="value"
        />
      );
    }
    
    export default CustomBarChart;