reactjsmaterial-uimui-xsparklinesmui-x-charts

MUI Sparkline: show the showHighligh always and with different colors based on condition


I have a sparkline chart from MUI for react as follows

import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';

export default function BasicSparkLine() {
  return (
    <Stack direction="row" sx={{ width: '100%' }}>
      <Box sx={{ flexGrow: 1 }}>
            <SparkLineChart
              data={[10, 20 , 30, 40, 0, -10, 25]}
              xAxis={{
                scaleType: 'point',
                data: [1, 2, 3, 4, 5, 6, 7, 8],
              }}
              height={100}
              width={600}
              showHighlight
            />
      </Box>
    </Stack>
  );
}

If "showHighlight" is set to true, on hover of the sparkline chart, we can see a highlight coming on the chart on each xaxis point.

Q1: Is there a way to have those highlighted points always shown ?

Q2: IS there a possibility to show the highlighted points in different colors based on the xaxis value of that exact point

Any help or suggestion is much appreciated. Thanks in advance

Thanks,


Solution

  • For anyone who are having similar issues. I came to know that we can use the <Indicator /> to achieve this. Adding the same code as well.

    import * as React from "react";
    import Stack from "@mui/material/Stack";
    import Box from "@mui/material/Box";
    import { SparkLineChart } from "@mui/x-charts/SparkLineChart";
    import {
      useXScale,
      useYScale,
      unstable_useLineSeries
    } from "@mui/x-charts/hooks";
    
    function Indicator({ dataIndex }: { dataIndex: number }) {
      const xScale = useXScale();
      const yScale = useYScale();
      const lineSeries = unstable_useLineSeries();
    
      const yData = lineSeries.series[lineSeries.seriesOrder[0]].data;
      const xData = xScale.domain();
    
      const xValue = xData[dataIndex];
      const yValue = yData[dataIndex];
      return (
        <circle
          cx={xScale(xValue)}
          cy={yScale(yValue)}
          r={5}
          fill={yValue > 4 ? "green" : "red"}
        />
      );
    }
    export default function BasicSparkLine() {
      return (
        <Stack direction="row" sx={{ width: "100%" }}>
          <Box sx={{ width: 300 }}>
            <SparkLineChart
              plotType="line"
              data={[1, 4, 2, 5, 7, 2, 4, 6]}
              height={100}
            >
            {[0, 1, 2, 3, 4, 5, 6, 7].map((tNew) => (
              <Indicator dataIndex={tNew} />
            ))}
            </SparkLineChart>
          </Box>
        </Stack>
      );
    }