d3.js堆积了不同颜色/图例的图表

时间:2014-02-11 16:53:27

标签: javascript 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);
    })    

1 个答案:

答案 0 :(得分:2)

请参阅this

调色板 在d3中,可以通过比例访问内置调色板。好吧,即使在protovis中,它们一直是有序的尺度,只是没有这样称呼。 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.