javascript 如何在 D3 中沿 Xaxis 设置自定义刻度?或命名条形图中的条形?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17089245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:02:59  来源:igfitidea点击:

How do I set custom ticks along the Xaxis in D3? or name the bars in a bar chart?

javascriptd3.jsbar-chartdata-visualization

提问by Keith Johnson

I'm trying to create a bar chart with custom values for each bar along the xAxis in D3, and thought I'd try to use the tickValues. Just to try it out I gave it some dummy data but it doesn't work like this:

我正在尝试为 D3 中沿 xAxis 的每个条形创建一个带有自定义值的条形图,并认为我会尝试使用 tickValues。只是为了尝试一下,我给了它一些虚拟数据,但它不能像这样工作:

  var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient("bottom")

    .tickValues(['hi','b','c','d','e']);

Here's the xScale:

这是 xScale:

gon.votes.length is an array of total votes counts for EACH answer and functionally is there only to return how many bars there will be for a specific survey question(this is a survey app fyi)

gon.votes.length 是每个答案的总票数数组,功能上仅用于返回特定调查问题将有多少条(这是一个调查应用程序仅供参考)

  var xScale = d3.scale.linear()
    .domain([0,gon.votes.length])
    .range([0,w]);

Finally, when I call

最后,当我打电话

function(d){ return d.title}

This will extract the appropriate title for each bar.

这将为每个条提取适当的标题。

Also here is the html of the ticks of the xAxis that gets rendered: NaN

这里也是被渲染的 xAxis 刻度的 html:NaN

Any tips on how to put this along the xAxis? Is trying to modify the ticks the wrong approach?

关于如何将其沿 xAxis 放置的任何提示?试图修改刻度是错误的方法吗?

回答by elsherbini

Ah, I see you were using a linear scale. In this case you need an ordinal scale, since the domain is a set of discrete values (the list of titles).

啊,我看到你在使用线性比例尺。在这种情况下,您需要一个序数比例,因为域是一组离散值(标题列表)。

Working example: http://tributary.io/inlet/5775047There are comments in the code for the axis part.

工作示例:http: //tributary.io/inlet/5775047轴部分的代码中有注释。

The issue is that the range array needs to have as many values as there are labels in the domain array. Otherwise it recycles. In your case, the first label was on 0, then w, then 0, then w, and so on.

问题是范围数组需要具有与域数组中的标签一样多的值。否则它会回收。在您的情况下,第一个标签在 0 上,然后是 w,然后是 0,然后是 w,依此类推。

To get the titles dynamically from the array of data, you need to use the map method on the array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

要从数据数组中动态获取标题,您需要对数组使用 map 方法。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Working example with dynamic titles: http://tributary.io/inlet/5775215

动态标题的工作示例:http: //tributary.io/inlet/5775215