【问题标题】:Changing text of the ticks in the axis更改轴中刻度的文本
【发布时间】:2018-04-28 17:18:10
【问题描述】:
我正在创建一个条形图,我想更改我的刻度文本。在数据集中,我将第一个单词(例如,食物)作为列头,但我想显示为文本“食物、饮料和烟草”。
我尝试过这样做,但它不起作用:
var xAxis = d3.axisBottom(xScale)
.tickFormat(function(d) { if (text=== "food"){
return "Food, drinks and tobacco"
}; })
我无法在 CSV 中设置该标题,因为如果列名中间有空格,D3 无法读取它们。
【问题讨论】:
标签:
javascript
d3.js
axis-labels
【解决方案1】:
这里有两个问题。首先,您使用的参数是d,而不是text。其次,没有else,您将无法正确返回其他刻度。
所以,应该是:
if (d === "Food") {
return "Food, drinks and tobacco"
} else {
return d
};
或者更简单,使用三元运算符:
return d === "Food" ? "Food, drinks and tobacco" : d;
这是一个基本的演示(使用 y 轴以获得更好的可读性):
var svg = d3.select("svg");
var scale = d3.scalePoint()
.range([20, 130])
.domain(["Food", "Clothing", "Transportation", "Health"]);
var axis = d3.axisLeft(scale)
.tickFormat(function(d) {
return d === "Food" ? "Food, drinks and tobacco" : d;
})
var gY = svg.append("g")
.attr("transform", "translate(150,0)")
.call(axis);
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>
关于你的最后一段:
我无法在 CSV 中设置该标题,因为如果列名中间有空格,D3 无法读取它们。
这是不正确的,这与 D3 无关。这是一个 JavaScript 问题:对于带有空格的属性名称,只需使用括号表示法:
var someObject = {
"a property name with spaces": 42
};
console.log(someObject["a property name with spaces"])