我想使用字符串作为 x 轴上刻度的标签(例如,第 1 年、第 2 年等,而不是 0、1、2 等)来创建条形图。
我首先使用 x 轴的数值(例如 0、1、2、3 等),如下所示:
1)我生成我的范围:
x = d3.scale.ordinal()
.domain(d3.range(svg.chartData[0].length)) //number of columns is a spreadsheet-like system
.rangeRoundBands([0,width], .1);
y = d3.scale.linear()
.domain(Math.min(d3.min(svg.chartData.extent),0), Math.max(d3.min(svg.chartData.extent),0)])
.range([height, 0])
.nice();
2)制作轴:
d3.svg.axis()
.scale(x);
3)重绘坐标轴:
svg.select(".axis.x_axis")
.call(make_x_axis().orient("bottom").tickSubdivide(1).tickSize(6, 3, 0));
这适用于默认的数字轴标签。
如果我尝试像这样对 x tickValues 使用字符串数组....
d3.svg.axis()
.scale(x).tickValues(svg.pointsNames); //svg.pointsNames = ["Year 1", "year 2", etc.]
...当我重新绘制图表时(无论是否更改数据/设置),标签都会像这样交换。
注意第 1 列如何取代第 0 列,反之亦然。
你知道为什么会发生这种情况吗?
最佳答案
更新
只需对 svg.pointsNames
进行排序,然后再将它们应用为 tickValues。确保对它们进行排序的方式与对数据进行排序的方式完全相同。这样,标签和刻度值之间始终保持一对一的映射。
如果可以的话,请查看 tickFormat` function这里。这对我来说似乎是更好的选择。
//Tick format example
chart,xAxis.tickFormat(function(d, i){
return "Year" + d //"Year1 Year2, etc depending on the tick value - 0,1,2,3,4"
})
关于javascript - D3 - 使用字符串作为轴刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11772115/