The Old County
The Old County

Reputation: 89

d3.js stacked chart with different colors/legends

I'm working on an application - where each column - may contain different type of topics.

This current demo shows an ordinary stacked chart.

http://jsfiddle.net/LsMZp/

But if I wanted to establish different topics/legends/colors of each column. What would be the best way of going about it?

would it be a case of creating a multi-dimensional array for the color array

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);
    })    

Upvotes: 2

Views: 5735

Answers (1)

Muath
Muath

Reputation: 4417

See this

Color palettes In d3, built-in color palettes can be accessed through scales. Well, even in protovis they had been ordinal scales all along, only not called this way. There are 4 built-in color palette in protovis: d3.scale.category10(), d3.scale.category20(), d3.scale.category20b(), and d3.scale.category20c().

A palette like d3.scale.category10() works exactly like an ordinal scale.

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.

Upvotes: 2

Related Questions