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

如何自定义MUI X Charts距离-海拔折线图的Tooltip样式与内容

自定义距离-海拔折线图Tooltip的实现方案

针对你提出的Tooltip自定义需求,直接修改LineChart的配置即可实现,以下是调整后的完整代码:

<LineChart
    margin={{ top: 5, bottom: 60, left: 55, right: 0 }} // 加大底部margin给Tooltip预留空间
    xAxis={[
        {
            min: Math.min(...xAxis),
            max: Math.max(...xAxis),
            data: xAxis,
            valueFormatter: (element) => `${element} km`,
        },
    ]}
    yAxis={[
        {
            tickNumber: 5,
            min: Math.min(...yAxis),
            max: Math.max(...yAxis),
            valueFormatter: (element) => `${element} m`,
        },
    ]}
    series={[
        {
            data: yAxis,
        },
    ]}
    // 新增Tooltip自定义配置
    tooltip={{
        // 1. 固定Tooltip在图表底部居中位置
        position: 'bottom',
        // 2-4. 处理距离值格式
        formatter: (datum) => {
            const formattedDistance = parseFloat(datum.x)
                .toFixed(2) // 四舍五入保留2位小数
                .replace(/,/g, ''); // 移除千位分隔符
            return {
                name: '距离',
                value: `${formattedDistance} m`,
            };
        },
        // 可选:设置低调样式,降低视觉存在感
        style: {
            backgroundColor: '#f5f5f5',
            fontSize: '12px',
            borderColor: '#ddd',
        },
    }}
/>

关键修改说明:

  • 调整Tooltip位置:通过tooltip.position: 'bottom'将Tooltip固定在图表底部,同时把margin.bottom从30调整为60,避免Tooltip和图表内容重叠。
  • 格式化距离值:在tooltip.formatter中对x轴数据做处理:
    • 用parseFloat转换为数值类型,避免字符串操作出错;
    • toFixed(2)实现四舍五入保留两位小数;
    • replace(/,/g, '')全局移除千位分隔符;
    • 最后拼接m后缀。
  • 低调样式优化:可选的style配置可以让Tooltip视觉上更低调,你可以根据需求调整颜色、字号等参数。

内容的提问来源于stack exchange,提问作者Timothée Billiet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:27:05