簡體   English   中英

在條形圖中使用序數比例('d3.scale.ordinal')作為x軸

[英]Using an ordinal scale ('d3.scale.ordinal') for the x-axis in a bar chart

我有一個像這樣的數據數組:

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

我在用:

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

我想創建一個條形圖

  • x軸具有字母名稱,和
  • y軸具有字母表的出現次數。

問題:如何在x軸上繪制帶有有序刻度的條形圖?

我的代碼:

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的值,並將這些值合並到域中。 我怎樣才能做到這一點?

兩件事情:

  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/reblace/tbamW/156/

出於某種原因,我無法使renderHorizontalGridLines()renderVerticalGridLines()工作,但其余的都很好。

添加

.x(d3.scale.ordinal().domain(data.map(function (d) {return d.Alphabet_Type; })))

解決了這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM