You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MUI SparkLine:如何始终显示高亮并按X轴值设置不同颜色?

关于MUI SparkLineChart的两个问题解决方案

原始示例代码

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>
  );
}

Q1:让高亮点始终显示

SparkLineChart的showHighlight默认仅在鼠标悬停时触发高亮,要让所有高亮点始终显示,可通过highlightedItems指定所有数据点的索引,配合highlightScope确保高亮生效:

<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
  // 指定所有索引的点为高亮状态
  highlightedItems={{ series: [{ dataIndex: [0,1,2,3,4,5,6] }] }}
  // 确保高亮作用于单个数据点
  highlightScope={{ highlighted: 'item' }}
/>

如果数据长度动态变化,可通过Array.from自动生成索引数组:

highlightedItems={{ 
  series: [{ 
    dataIndex: Array.from({length: 7}, (_, i) => i) 
  }] 
}}

Q2:根据X轴值为高亮点设置不同颜色

可以通过自定义renderHighlight函数,在渲染高亮元素时根据对应X轴值动态设置颜色:

<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
  highlightedItems={{ series: [{ dataIndex: [0,1,2,3,4,5,6] }] }}
  highlightScope={{ highlighted: 'item' }}
  // 自定义高亮元素渲染逻辑
  renderHighlight={({ dataIndex, xAxisData }) => {
    const xValue = xAxisData[dataIndex];
    // 根据X值设置颜色规则
    let color;
    if (xValue < 3) color = '#ff4444';
    else if (xValue < 6) color = '#ffbb33';
    else color = '#00C851';
    
    return (
      <circle
        cx="0"
        cy="0"
        r="6"
        fill={color}
        stroke="#fff"
        strokeWidth={2}
      />
    );
  }}
/>

也可通过highlightStyle的回调函数实现(适用于简单颜色逻辑):

highlightStyle={{
  item: (props) => {
    const xValue = props.xAxisData[props.dataIndex];
    return {
      fill: xValue > 5 ? '#2196F3' : '#F44336',
      stroke: '#fff',
      strokeWidth: 2,
      r: 6
    };
  }
}}

内容的提问来源于stack exchange,提问作者SM079

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 01:00:02