在使用D3 v4的this axis label example中,它将x轴和文本标签添加为svg下的单独节点。
// Add the x Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// text label for the x axis
svg.append("text")
.attr("transform",
"translate(" + (width/2) + " ," +
(height + margin.top + 20) + ")")
.style("text-anchor", "middle")
.text("Date");
当我链接上面的代码(因此移动x轴组下的文本元素):
// Add the x Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.append("text")
.style("text-anchor", "middle")
.text("Date");
然后我的轴标题不再可见(见下面的截图)。我仍然可以在x轴组下的DOM中找到我的文本元素,但它在渲染的HTML中不存在。
我想知道:
D3轴标签必须单独添加?
不,它没有。你可以链,这不是问题。这里的问题是文本元素的fill
。
正如您在链接的屏幕截图中看到的那样,容器组的“无”为fill
。由于文本继承了父级的属性/样式,因此您必须将其fill
从“none”更改为您想要的任何颜色:
var svg = d3.select("svg");
var xScale = d3.scaleLinear()
.domain([1, 10])
.range([10,390]);
var xAxis = d3.axisBottom(xScale);
var gX = svg.append("g")
.attr('class', 'axis')
.attr("transform","translate(0,40)")
.call(xAxis)
.append("text")
.attr("fill", "black")//set the fill here
.attr("transform","translate(120, 40)")
.text("Hello World!!!");
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400" height="80"></svg>
PS:这个问题在D3 v3.x中不会发生。