最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change colour of single bar in Material UI when using BarChart? - Stack Overflow

programmeradmin1浏览0评论

I'm using the following code to make a Graph:

const namesArray = Object.values(tableData).map(item => item.name);
  const valuesArray = Object.values(tableData).map(item => item.value);

  return (
    <Box>
      <SimpleCard title="Cell Voltages">
        <BarChart
          width={750}
          height={300}
          series={[
            { data:valuesArray, id: 'cId'},
          ]}
          xAxis={[{ data: namesArray, scaleType: 'band' }]}
        />
      </SimpleCard>
    </Box>
  );

And I'm getting this as output:

However, I need to change the colour of a particular bar in this graph (currently highest and lowest values), but I can't seem to find any way to do this. I also didn't understand the documentation of the API on their website properly. What should I do to get the result I want?

Thank You.

I'm using the following code to make a Graph:

const namesArray = Object.values(tableData).map(item => item.name);
  const valuesArray = Object.values(tableData).map(item => item.value);

  return (
    <Box>
      <SimpleCard title="Cell Voltages">
        <BarChart
          width={750}
          height={300}
          series={[
            { data:valuesArray, id: 'cId'},
          ]}
          xAxis={[{ data: namesArray, scaleType: 'band' }]}
        />
      </SimpleCard>
    </Box>
  );

And I'm getting this as output:

However, I need to change the colour of a particular bar in this graph (currently highest and lowest values), but I can't seem to find any way to do this. I also didn't understand the documentation of the API on their website properly. What should I do to get the result I want?

Thank You.

Share Improve this question edited Mar 17 at 22:12 Olivier Tassinari 8,6916 gold badges25 silver badges28 bronze badges asked Nov 23, 2023 at 12:37 Divyanshu BhujbalDivyanshu Bhujbal 591 silver badge5 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 4

Per-bar coloring is possible by passing a colorMap of type "ordinal" to the xAxis, see documentation.

In the version here, I set the minimum value to be red and the maximum value to be green. See the CodeSandbox link below to play with it yourself.

import { Box } from "@mui/material";
import { BarChart } from "@mui/x-charts";
import Card from "@mui/material/Card";

export default function ChartPerBarColoring() {
  const tableData = {
    1: { name: "Cell1", value: 10 },
    2: { name: "Cell2", value: 11 },
    3: { name: "Cell3", value: 13 },
    4: { name: "Cell4", value: 12 },
    5: { name: "Cell5", value: 9 },
    6: { name: "Cell6", value: 10 },
  };
  const namesArray = Object.values(tableData).map((item) => item.name);
  const valuesArray = Object.values(tableData).map((item) => item.value);

  // make array of bar colors, highlighting max/min
  const minVal = Math.min(...valuesArray);
  const maxVal = Math.max(...valuesArray);
  const barColors = valuesArray.map((val) => {
    if (val === minVal) {
      return "red";
    } else if (val === maxVal) {
      return "green";
    } else {
      return null; // non-max and non-min values take default color of series
    }
  });

  return (
    <Box>
      <Card title="Cell Voltages">
        <BarChart
          width={750}
          height={300}
          series={[{ data: valuesArray, id: "cId" }]}
          xAxis={[
            {
              data: namesArray,
              scaleType: "band",
              colorMap: {
                type: "ordinal",
                values: namesArray,
                colors: barColors,
              },
            },
          ]}
        />
      </Card>
    </Box>
  );
}

I think I was having similar issue. I just wanted single bars with different colors but they always were same color. My hack was to fill it out as if its one of the multibar charts, but with zero values where I didn't want the data. Then I just made the bars wider with a negative barGapRatio. This allows the color palette to be modified and it will affect each individual bar, or you can just add a color to each object with data.

<BarChart
            layout='horizontal'
            /*COLOR PALETTE OPTION*/
            colors={cheerfulFiestaPalette}
            /*CHANGE THE BAR SIZE WITH NEGATIVE barGapRatio*/
            yAxis={[{ barGapRatio: -1, scaleType: 'band', data: ['A', 'B', 'C', 'D'] }]}
            series={[
                {
                    /*INDIVIDUAL COLOR OPTION*/
                    color:['red']
                    data: [120000000, 0, 0, 0],
                },
                {
                    data: [0, 180000000, 0, 0],
                },
                {
                    data: [0, 0, 700000000, 0],
                },
                {
                    data: [0, 0, 0, 1000000000],
                }
            ]}
            /*ADD THIS TO HIDE ZERO VALUES IN TOOLTIP*/
            tooltip={{ trigger: 'item' }}
            width={500}
            height={250}
        />
// Assuming you have already created the chart and have access to its container element

// Get the container element of the chart
const chartContainer = document.getElementById('chart-container');

// Assuming you have already created the chart using Material-UI BarChart

// Get the individual bars inside the chart
const bars = chartContainer.querySelectorAll('.recharts-bar-rectangles');

// Define the index of the bar you want to change the color for
const targetBarIndex = 0; // Change this to the index of the bar you want to target

// Define the color you want to change the bar to
const newColor = 'green'; // Change this to the desired color

// Check if the target bar index is valid
if (targetBarIndex >= 0 && targetBarIndex < bars.length) {
  // Access the target bar and update its style
  bars[targetBarIndex].style.fill = newColor;
} else {
  console.error('Invalid target bar index');`enter code here`
}

I just got two, use nth child instead.

sx={{
  "& .MuiBarElement-root:first-child": {
    fill: "red",
  },
  "& .MuiBarElement-root:last-child": {
    fill: "black",
   },
}}

Here is a minimal example with hardcoded data on how to set the colours and test them:

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

...

   <BarChart
        xAxis={[
          {
            scaleType: 'band',
            data: ['Completed', 'In Progress', 'To do'],
            colorMap: {
              type: 'ordinal',
              values: ['Completed', 'In Progress', 'To do'],
              colors: ['red', 'blue', 'green'],
            },
          },
        ]}
        yAxis={[{ scaleType: undefined }]}
        series={[{ data: [0, 1, 12] }]}
        width={500}
        height={300}
      />

you can't change the color of specific bar but if you want then using css class MuiBarElement-root and give nth-child() and add your color value may it works.

Other then if you want to change all bars color then you can use colors attribute for give custom color

check here : https://stackblitz./edit/react-jwxeyu?file=Demo.tsx

发布评论

评论列表(0)

  1. 暂无评论