2014-09-12 113 views
0

值基本上,我試圖重新創建此圖這是在Excel中創建:JSON鍵x軸,y的

enter image description here

到目前爲止我的代碼是這樣的......

var theData = [ 
     { 
     'FB':4, 
     'Mv':4, 
     'CB':5, 
     'SL':3, 
     'CH':2, 
     'OT':2, 
     'Ctrl':6, 
     'Cmd':6, 
     'Del':5, 
     'AA':6, 
     }, 
     { 
     'FB':2, 
     'Mv':3, 
     'CB':4, 
     'SL':5, 
     'CH':4, 
     'OT':3, 
     'Ctrl':5, 
     'Cmd':6, 
     'Del':6, 
     'AA':5, 
     }, 
     etc... 
    ]; 

    var margin = {top:10, right:10, bottom:30, left:40}, 
     width = 600 - margin.left - margin.right, 
     height = 400 - margin.top - margin.bottom; 

    var x = d3.scale.ordinal() 
     .domain(d3.keys(theData[0])) 
     .rangeRoundBands([0, width]); 

    var y = d3.scale.linear() 
     .domain([2,8]) 
     .range([height,0]); 

    var xAx = d3.svg.axis() 
     .scale(x) 
     .orient('bottom') 
    var yAx = d3.svg.axis() 
     .scale(y) 
     .orient('left') 
     .ticks(3); 

    var svgContainer = d3.select('#d3Stuff').append('svg') 
     .attr('width',width + margin.left + margin.right) 
     .attr('height',height + margin.top + margin.bottom) 
     .style('border','1px solid black') 
     .append("g") 
     .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

    svgContainer.append("g") 
     .attr("class", "x axis") 
     .attr("transform", "translate(0," + height + ")") 
     .call(xAx) 
     .append("text") 
     .attr("class", "label") 
     .attr("x", width) 
     .attr("y", -6) 
     .style("text-anchor", "end"); 

    svgContainer.append("g") 
     .attr("class", "y axis") 
     .call(yAx) 
     .append("text") 
     .attr("class", "label") 
     .attr("transform", "rotate(-90)") 
     .attr("y", 6) 
     .attr("dy", ".71em") 
     .style("text-anchor", "end"); 

我在試圖讓數據對象中的值出現圓圈時遇到問題。我希望他們排列X軸鍵,顯然。如果我至少可以獲得初始值,那麼我可以稍後計算最小/最大/平均值。

這裏是代碼創建至今:

enter image description here

任何幫助將是真棒!

回答

1

您可以使用序數標度來查找使用鍵的任何圓的x位置(因爲序號域由鍵組成)。例如x("FB")x("Mv")

要創建圓圈,您需要使用enter,update,exit等東西以典型的d3方式綁定到數組。

既然你的數據是一個散列,而不是一個數組,你需要先將它放入一個數組的形式。這很容易使用d3.map()theData(我建議去除內theData周圍的哈希數組[]包裝,因爲它沒有做任何事情,但仍然):

d3.map(theData[0]).entries() 
/* returns [ 
    { 
    "key": "FB", 
    "value": 4 
    }, 
    { 
    "key": "Mv", 
    "value": 4 
    }, 
    { 
    "key": "CB", 
    "value": 5 
    }, 
    { 
    "key": "SL", 
    "value": 3 
    }, 
    { 
    "key": "CH", 
    "value": 2 
    }, 
    ... 
]" 

一旦有了這種關聯數組,你可以做平常data(...)結合,追加圓圈,然後用一些定位他們像

.attr("x", function(d) { return x(d.key); }) 
+0

實際上的數據是比我貼越多,陣列中的多個對象: [{ 「FB」:4, 'MV':4, 'CB':5, 'SL':3, 'CH':2, 'OT':2, Ctrl鍵:6, 'Cmd的':6, '德爾':5, 'AA':6, }, { 'FB':3, 'MV':2, 'CB':3, 'SL':4, 'CH' :5, 'OT':5, Ctrl鍵:7, 'Cmd的':5, '德爾':4, 'AA':3, },等... ] 我將不得不計算分鐘/最大/平均所有這些 – ksumarine 2014-09-12 17:00:35