D3 how to create stack diagrams with different colors

the desired effect is as follows:

d3stacked bar chart:

the color of the two different columns is the same. The code can see here . The question is, how can I create the kind of bar chart that I want, each column has a different color ? Thank you ~


indeed, as mentioned in @ Randal , use a function to generate the value of fill, such as in the above example . We can make the following modifications to achieve different colors for different columns:

var layer = svg.selectAll(".stack")
            .data(dataStackLayout)
            .enter().append("g")
            .attr("class", "stack")
            
            // 
            /* .style("fill", function (d, i) {
                return color(i);
            }); */

    layer.selectAll("rect")
            .data(function (d) {
                return d;
            })
            .enter().append("rect")
            .attr("x", function (d) {
                return x(d.x);
            })
            .attr("y", function (d) {
                return y(d.y + d.y0);
            })
            .attr("height", function (d) {
                return y(d.y0) - y(d.y + d.y0);
            })
            .attr("width", x.rangeBand())
            
            // 
            .style("fill", function (d, i, j) {  // :d i rectj rect 
               return color((j * 2) + i);
            });
           

.attr("fill", function(d){ return d.y > 6 ? "-sharpFF0033" : "-sharp666666"});

from: https://stackoverflow.com/que.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e3c909-446c7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e3c909-446c7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?