关于javascript:d3.js中的轴刻度标签样式

Style of axis tick labels in d3.js

以下脚本创建带有三个标签和一个标题的点比例轴。正文css选择器定义了正文中所有文本元素的字体系列和字体大小。尽管轴标题受css规则的影响,但轴刻度标签本身不受限制,尽管它们本身是文本元素。我知道我可以使用.axis文本选择器设置刻度标签样式。也许我在这里遗漏了一些明显的东西,但是是什么阻止了使用主体选择器呈现刻度标签呢?

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!doctype html>
<meta charset="utf-8">

<script src="d3.min.V4.js">

<style>

body {
  font-family: Courier;
  font-size: 18px;
}

</style>

<body>

</body>



var margin = {top: 20, right: 60, bottom: 40, left: 70},
    width = 600,
    height = 100;

var svg = d3.select('body').append('svg')
                       .attr('width', width)
                       .attr('height', height);

var xScale = d3.scalePoint().domain(["blue","red","green"]).range([margin.left, width-margin.right]);

// Add the x Axis
 svg.append("g")
     .attr("transform","translate(0," + (height - margin.bottom) +")")
     .attr("class","axis")
   .call(d3.axisBottom(xScale)
     );

//x axis title
svg.append('text')
   .text('Colors')
   .attr('x', width/2)
   .attr('y', height - 5)
   .style("text-anchor","middle");

如Gerardo所述,默认情况下,API将使用填充#000进行绘制。
解决方法是重新选择文本并重新设置其样式。
看起来像这样:

1
2
3
4
5
6
7
8
9
10
11
12
var xScale = d3.scalePoint().domain(["blue","red","green"]).range([margin.left, width-margin.right]);

// Add the x Axis
var xTicks = svg.append("g")
     .attr("transform","translate(0," + (height - margin.bottom) +")")
     .attr("class","axis")
   .call(d3.axisBottom(xScale)
     );

xTicks.selectAll('text').attr('fill', function(d){
    return d;
  });

根据API,轴生成器会自动设置容器g元素中刻度的字体大小和字体系列,这是默认样式(从API示例复制的代码):

1
2
3
4
5
6
7
8
9
//styles applied to the outer g element:
<g fill="none" font-size="10" font-family="sans-serif" text-anchor="middle">
    <path class="domain" stroke="#000" d="M0.5,6V0.5H880.5V6"></path>
    <g class="tick" opacity="1" transform="translate(0,0)">
        <line stroke="#000" y2="6" x1="0.5" x2="0.5"></line>
        <text fill="#000" y="9" x="0.5" dy="0.71em">0.0</text>
    </g>
    //etc...
</g>

因此,由于特殊性和优先级规则,这种样式似乎优于您的body CSS样式。

要更改刻度,您必须在CSS中指定text(或使用类或ID)。