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

如何修改MUI X Charts的XY坐标轴及刻度文字颜色

解决MUI X Charts XY坐标轴及刻度文字颜色修改问题

你之前通过sx选择全局类名的方式不生效,是因为MUI X Charts的轴样式需要通过组件自身的axis配置项定制,以下是修改后的可运行代码:

import * as React from "react";
import { LineChart } from "@mui/x-charts/LineChart";
import Stack from "@mui/material/Stack";
import ToggleButton from "@mui/material/ToggleButton";
import ToggleButtonGroup from "@mui/material/ToggleButtonGroup";

const Tableau3 = ["#4e79a7", "#f28e2c", "#e15759"];

const chartsParams = {
  margin: { bottom: 20, left: 25, right: 5 },
  height: 300
};
export default function BasicColor() {
  const [color, setColor] = React.useState("#4e79a7");

  const handleChange = (event, nextColor) => {
    setColor(nextColor);
  };

  return (
    <Stack
      direction="column"
      spacing={2}
      alignItems="center"
      sx={{ width: "100%" }}
    >
      <LineChart
        {...chartsParams}
        // 配置XY轴的线条、刻度、文字颜色
        xAxis={[{
          line: { stroke: "blue" }, // X轴主线颜色
          tick: { stroke: "blue" }, // X轴刻度短线颜色
          tickLabel: { fill: "blue" } // X轴刻度文字颜色
        }]}
        yAxis={[{
          line: { stroke: "blue" }, // Y轴主线颜色
          tick: { stroke: "blue" }, // Y轴刻度短线颜色
          tickLabel: { fill: "blue" } // Y轴刻度文字颜色
        }]}
        series={[
          {
            data: [15, 23, 18, 19, 13],
            label: "example",
            color
          }
        ]}
      />
      <ToggleButtonGroup
        value={color}
        exclusive
        onChange={handleChange}
      >
        {Tableau3.map((value) => (
          <ToggleButton key={value} value={value} sx={{ p: 1 }}>
            <div
              style={{
                width: 15,
                height: 15,
                backgroundColor: value,
                display: "inline-block"
              }}
            />
          </ToggleButton>
        ))}
      </ToggleButtonGroup>
    </Stack>
  );
}

关键说明

  • 这种通过xAxis/yAxis配置项直接指定样式的方式,是MUI X Charts官方推荐的定制方案,优先级更高且适配明暗模式的自动切换逻辑。
  • 如果需要额外定制轴的其他样式(比如字体大小、间距),可以在对应轴的配置中添加sx属性,示例:
    xAxis={[{
      tickLabel: { fill: "blue" },
      sx: {
        '.MuiChartsAxis-tickLabel': { fontSize: 12, fontWeight: 500 }
      }
    }]}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:22:46