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

如何在d3中为坐标轴的单个文本标签单独设置颜色

解决方案

你之前的代码问题出在将颜色数组绑定到了整个x轴的容器<g>元素上,样式会作用到所有轴元素,自然无法单独给每个文本标签设置差异化颜色。正确做法是在x轴渲染完成后,单独选中每个刻度的文本元素,按索引匹配对应颜色即可。

核心修改点

  • 移除容器<g>上的data绑定和样式设置逻辑
  • 渲染完x轴后,选中所有.tick text元素,按索引设置fill属性(文本不需要设置stroke,避免字体变粗发糊)

修改后可直接运行的完整代码如下:

<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>Colored x axis</title>
</head>
<body>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<script>

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 40},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");
          
 var strings = ["Data Set 1","Data Set 2","Data Set 3"];         
 
 var xtop      = d3.scaleBand().domain(strings).range([0, width]);
 var xAxisTop  = d3.axisTop(xtop);
 var colors = ["#AC5503","#DF3511","#AE9922"];
 
 // 先正常渲染x轴
 svg
  .append('g')
  .attr('transform', 'translate(0,10)')
  .call(xAxisTop.tickSize(0))
  .select(".domain").remove()
  // 单独选中所有刻度文本设置颜色
  .selectAll(".tick text")
  .attr("font-size", "22px")
  .attr("fill", (d, i) => colors[i]);

</script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:06:05