对条形图中的 x 轴使用序数刻度 ('d3.scale.ordinal') [英] Using an ordinal scale ('d3.scale.ordinal') for the x-axis in a bar chart

查看:34
本文介绍了对条形图中的 x 轴使用序数刻度 ('d3.scale.ordinal')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据数组:

I have a data array like this:

var data = [{"Alphabet_Type":"a"}, {"Alphabet_Type":"b"}, {"Alphabet_Type":"a"}];

我正在使用:

  • dc.js
  • crossfilter.js
  • d3.js

我想创建一个条形图:

  • 具有字母名称的 x 轴,以及
  • 具有字母表出现次数的 y 轴.

问题:如何在 x 轴上绘制带有有序刻度的条形图?

Question: How can I plot a bar chart with an ordinal scale on the x-axis?

我的代码:

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

最后,我还有另一个问题是 Alphabet_Type 不会有可预测的值.所以我需要通过 crossfilter.js 获取 Alphabet_Type 的值并将这些值合并到域中.我该怎么做?

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.js and incorporate those values into the domain. How can I do this?

推荐答案

两件事:

  1. 通过dc.units.ordinal 作为.xUnits().
  2. 序数比例函数传递给.x().

我的意思是:

.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

请参阅此 JSFiddle:http://jsfiddle.net/reblac/tbamW/156/

See this JSFiddle: http://jsfiddle.net/reblace/tbamW/156/

出于某种原因,我无法获得 renderHorizo​​ntalGridLines()renderVerticalGridLines() 工作,但其余的都很好.

For some reason, I couldn't get renderHorizontalGridLines() or renderVerticalGridLines() to work, but the rest is good.

这篇关于对条形图中的 x 轴使用序数刻度 ('d3.scale.ordinal')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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