D3 - 使用字符串轴刻度 [英] D3 - using strings for axis ticks

查看:142
本文介绍了D3 - 使用字符串轴刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用字符串作为x轴(例如,年1,年2,等等,而不是0,1,2等)的标记的条形图。

I want to crate a bar chart using strings as the labels for the ticks on the x-axis (e.g., Year 1, Year 2, etc instead of 0,1,2, etc).

我开始使用x轴的数字值(例如0,1,2,3等),如下:

I started by using the numeric values for the x-axis (e.g., 0,1,2,3, etc) as follows:

1)我生成了我的范围:

1) I generate my ranges:

     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));

这对于默认数字轴标签很有效。

This works well with default numeric axis labels.

如果我尝试为x tickValue使用一个字符串数组,像这样....

If I try to use an array of strings for the x tickValues like this....

     d3.svg.axis()
        .scale(x).tickValues(svg.pointsNames); //svg.pointsNames = ["Year 1", "year 2", etc.]

。 ..当我重绘图表(有或没有更改数据/设置),标签交换像这样。

... when I redraw the chart (with or without changes to the data/settings), the labels swap like this.


请注意,Col 1取代Col 0的位置,反之亦然。

Notice how Col 1 takes the place of Col 0 and vice versa.

知道为什么会发生这种情况?

Do you know why this happens?

推荐答案

更新

在将它们应用为tickValues之前,只需对 svg.pointsNames 进行排序。请确保按照与排序数据完全相同的方式进行排序。这样,您的标签和刻度值之间始终保持一一映射。

Just sort the svg.pointsNames before you apply them as tickValues. Make sure you sort them in exactly the same way that you sort your data. This way, a one-one mapping is always maintained between your labels and tick values.

如果可以,请查看 tickFormat` function 。这对我来说似乎是一个更好的选择。

Also if I may, check out the tickFormat` function here. This seems a better option to me.

//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"
})

这篇关于D3 - 使用字符串轴刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆