如何在 d3 中的轴上单独为文本标签着色?

How to color the text labels individually on an axis in d3?

我正在使用 d3 绘制多个数据集的散点图(点图)。

为此,我需要顶部的 x 轴来显示数据集的名称。但是这些文本标签必须与图中特定数据集的 points/circles 颜色相同,以查看哪些点属于哪个数据集。

我正在尝试使用“描边”和“填充”属性来执行此操作,但我无法使其工作。而且文字颜色都是一样的,而不是随心所欲的不同。

到目前为止,这是我的代码:

<!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"];
 
 svg
  .append('g')
  .data(colors)
    .attr('transform', 'translate(0,10)')
    .attr("style",(d,i) => "font-size:22px; stroke:" + colors[i] + "; fill:" + colors[i] + ";")
    .call(xAxisTop.tickSize(0))
    .select(".domain").remove();  

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

非常感谢任何帮助,谢谢。

添加轴后,您可以select所有刻度标签并相应地设置它们的属性。我已经更新了您的代码:

<!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: 30, 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).tickSize(0);
 var color = d3.scaleOrdinal()
    .domain(strings)
    .range(["#AC5503","#DF3511","#AE9922"]);
 
 svg.append('g')
  .call(xAxisTop)
  .call(g => g.selectAll('.tick > text')
      .attr('font-size', 22)
      .attr('fill', d => color(d)))
  .call(g => g.select('.domain').remove()); 

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