2014-02-11 73 views
2

我正在研究一個應用程序 - 其中每列可能包含不同類型的主題。d3.js不同顏色/圖例的堆疊圖表

這個當前的演示顯示了一個普通的堆棧圖。

http://jsfiddle.net/LsMZp/

但是,如果我想建立每列不同的主題/傳說/顏色。最好的辦法是什麼?

會是創建一個多維陣列的顏色陣列的情況下

var color = d3.scale.ordinal() 
    .range(["#20b2aa", "#fa8072", "#87ceeb", "#daa520", "#00bfff", "#dc143c", "#87cefa", "#90ee90", "#add8e6", "#d3d3d3"]); 


state.selectAll("rect") 
    .data(function(d) { 
     return d.ages; 
    }) 
    .enter().append("rect") 
    .attr("width", x.rangeBand())      
    .attr("y", function(d) { return y(d.y1); }) 
    .attr("height", function(d) { return y(d.y0) - y(d.y1); }) 
    .style("fill", function(d) { return color(d.name); })//; 
    .on("mouseover", function(d) { 
     //Get this bar's x/y values, then augment for the tooltip 
     var xPosition = parseFloat(d3.select(this.parentNode).attr("x")) + (x.rangeBand()/2) + 50; 
     var yPosition = parseFloat(d3.select(this).attr("y"))/2 + height/2; 
     //Update the tooltip position and value 
     d3.select("#tooltip") 
      .style("left", xPosition + "px") 
      .style("top", yPosition + "px")      
      .select("#value") 
      .text(d.name +" : " + d.hours); 
     //Show the tooltip 
     d3.select("#tooltip").classed("hidden", false); 
    }) 
    .on("mouseout", function() { 
     //Hide the tooltip 
     d3.select("#tooltip").classed("hidden", true); 
    })  
+0

這聽起來不像是這種類型的圖表適合您想要顯示的內容。也許是一系列或嵌套的[甜甜圈圖表](http://bl.ocks.org/mbostock/3887193)? –

+0

啊。我確實有一系列已經表示數據的嵌套圓環圖。我想知道如何壓縮它們以形成堆疊圖表。所以信息可以一目瞭然。我想我可以將信息顯示爲一系列單獨的堆積圖表。 –

+0

也許[堆積面積圖](http://nvd3.org/ghpages/stackedArea.html)呢? –

回答

2

參見this

調色板 D3中,內置的顏色調色板可通過秤進行訪問。那麼,即使在原型中,他們一直都是序級,只是沒有這樣調用。 protovis中有4種內置調色板:d3.scale.category10(),d3.scale.category20(),d3.scale.category20b()和d3.scale.category20c()。

像d3.scale.category10()這樣的調色板的工作方式與序數標度完全相同。

var p=d3.scale.category10(); 
var r=p.range(); // ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", 
         // "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"] 
var s=d3.scale.ordinal().range(r); 
p.domain(); // [] - empty 
s.domain(); // [] - empty, see above 
p(0); // "#1f77b4" 
p(1); // "#ff7f0e" 
p(2); // "#2ca02c" 
p.domain(); // [0,1,2]; 
s(0); // "#1f77b4" 
s(1); // "#ff7f0e" 
s(2); // "#2ca02c" 
s.domain(); // [0,1,2]; 

d3.scale.category10(1); // this doesn't work 
d3.scale.category10()(1); // this is the way. 
+0

http://jsfiddle.net/NYEaX/132/這是我將使用的堆疊圖表代碼。 –