2014-04-10 21 views
0

我想在酒窩js條形圖中添加y軸(成本)的酒吧圖表值。值正在增加,但在圖表外,因爲我認爲它無法找到x軸的正確比例。有什麼建議麼?在圖表外的條形圖中的酒窩js值

這裏是的jsfiddle:http://jsfiddle.net/Ra2xS/27/

var dim = {"width":590,"height":450}; //chart container width 
    var data = [{"date":"01-02-2010","cost":"11.415679194952766"},{"date":"01-03-2010","cost":"10.81875691467018"},{"date":"01-04-2010","cost":"12.710197879070897"}]; 


    function barplot(id,dim,data) 
    { 
     keys = Object.keys(data[0]); 
     var xcord = keys[0]; 
     var ycord = keys[1]; 
     var svg = dimple.newSvg(id, dim.width, dim.height); 

     var myChart = new dimple.chart(svg,data); 
     myChart.setBounds(60, 30, 505, 305);   

     var x = myChart.addCategoryAxis("x", xcord); 
     //var x = myChart.addTimeAxis("x", xcord, "%d-%m-%Y","%b %Y"); 
     x.addOrderRule(xcord); 
     x.showGridlines = true; 
     //x.timePeriod = d3.time.months; 

     var y = myChart.addMeasureAxis("y", ycord); 
     y.showGridlines = true; 
     y.tickFormat = ',.1f';  

     var s = myChart.addSeries(null, dimple.plot.bar); 
     var s1 = myChart.addSeries(null, dimple.plot.line); 
     s1.lineWeight = 3; 
     s1.lineMarkers = true; 

     myChart.draw(1500); 

      s.shapes.each(function(d) { 

       // Get the shape as a d3 selection 
       var shape = d3.select(this), 

       // Get the height and width from the scales 
       height = myChart.y + myChart.height - y._scale(d.height); 
       width = x._scale(d.width); //I think here is the problem 

       //alert(d.width); 
       // Add a text label for the value 
       svg.append("text") 

       // Position in the centre of the shape (vertical position is 
       // manually set due to cross-browser problems with baseline) 
       .attr("x", parseFloat(shape.attr("x")) + width/2 - 15) 
       .attr("y", parseFloat(shape.attr("y")) - height/2) 

       // Centre align 
       .style("text-anchor", "middle") 
       .style("font-size", "10px") 
       .style("font-family", "sans-serif") 

       // Make it a little transparent to tone down the black 
       .style("opacity", 0.7) 

       // Format the number 
       .text(d3.format(",.2f")(d.yValue)); 
      });  
    } 

barplot("body",dim,data); 

回答

0

您可以從元素直接得到的x位置和條寬。您可以通過將高度傳遞給量表獲得y位置 - 不需要偏移量。

.attr("x", parseFloat(shape.attr("x")) + parseFloat(shape.attr("width"))/2) 
.attr("y", y._scale(d.height)) 

完整演示here。我爲標籤添加了一個小的垂直偏移,因此它們不會與圓/線重疊。

+0

我只是寫了一條消息說,這將是不可能的,直到下一個版本(由於即將過渡後添加回調的能力),它似乎我錯了:) –

+0

這有點hacky,但在最壞的情況下,你可以使用'setTimeout',並在轉換持續時間外再加一點點。 –