javascript 对条形图中的 x 轴使用序数刻度 ('d3.scale.ordinal')
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18742406/
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
Using an ordinal scale ('d3.scale.ordinal') for the x-axis in a bar chart
提问by Arun
I have a data array like this:
我有一个这样的数据数组:
var data = [{"Alphabet_Type":"a"}, {"Alphabet_Type":"b"}, {"Alphabet_Type":"a"}];
I am using:
我在用:
- dc.js
- crossfilter.js
- d3.js
- dc.js
- 交叉过滤器.js
- d3.js
I want to create a bar chartwith:
我想创建一个条形图:
- the x-axis having an alphabet name, and
- the y-axis having number of occurrences of the alphabet.
- 具有字母名称的 x 轴,以及
- y 轴具有字母表的出现次数。
Question:How can I plot a bar chart with an ordinal scaleon the x-axis?
问题:如何在 x 轴上绘制带有序号刻度的条形图?
My code:
我的代码:
var data = [{"Alphabet_Type":"a"}, {"Alphabet_Type":"b"}, {"Alphabet_Type":"a"}];
var Filter = crossfilter(data);
var Dimension = Filter.dimension(function (d) { return d.Alphabet_Type; });
var Group = Dimension.group();
dc.barChart("#bar-chart")
.width(800)
.height(275)
.transitionDuration(0)
.margins({ top: 10, right: 50, bottom: 30, left: 40 })
.dimension(Dimension)
.group(Group)
.elasticY(false)
.elasticX(false)
.x(d3.scale.linear().domain([-1, 10]))
.y(d3.scale.linear().domain([0, 5]))
.centerBar(true)
.renderHorizontalGridLines(true)
.renderVerticalGridLines(true)
.brushOn(false);
Finally, I have another problem which is that Alphabet_Type
is not going to have predictable values. So I need to fetch the values for Alphabet_Type
via crossfilter.jsand incorporate those values into the domain. How can I do this?
最后,我还有另一个问题,那Alphabet_Type
就是不会有可预测的值。所以我需要Alphabet_Type
通过crossfilter.js获取值并将这些值合并到域中。我怎样才能做到这一点?
回答by reblace
Two things:
两件事情:
- Pass
dc.units.ordinal
as the parameter to.xUnits()
. - Pass an ordinal scalefunction to
.x()
.
dc.units.ordinal
作为参数传递给.xUnits()
.- 将序数比例函数传递给
.x()
。
Here's what I mean:
这就是我的意思:
.x(d3.scale.ordinal().domain(["", "a", "b", "c"])) // Need empty val to offset first value
.xUnits(dc.units.ordinal) // Tell dc.js that we're using an ordinal x-axis
See this JSFiddle: http://jsfiddle.net/reblace/tbamW/156/
看到这个 JSFiddle:http: //jsfiddle.net/reblac/tbamW/156/
For some reason, I couldn't get renderHorizontalGridLines()
or renderVerticalGridLines()
to work, but the rest is good.
由于某种原因,我无法上班renderHorizontalGridLines()
或renderVerticalGridLines()
无法工作,但其余的都很好。
回答by Arun
Adding
添加
.x(d3.scale.ordinal().domain(data.map(function (d) {return d.Alphabet_Type; })))
solved the problem.
解决了这个问题。