how to create a stacked bar chart with images in d3

1.5k Views Asked by At

i am trying to create a stacked bar chart with images on each rectangle and it was creating images separately in the body, can someone please help me in it. the output of my code is showing images in an another g class i need those images to be displayed in the respective rectangles.

d3.select("body").selectAll("rect")
.data(piedata)
.enter()
.append("svg:image")
.attr("xlink:href",function(d) {return d.data.image;})
.attr("width",50)
.attr("height",50)

js link : http://jsfiddle.net/sai20/5dzpc3wn/

1

There are 1 best solutions below

3
On BEST ANSWER

I propose you have a single data set because you are creating rectangle with one dataset on one section, then with the other dataset you making g group... in that group you are putting an image.

I would suggest have a single g per data in the dataset. And in that g append your image and rectangle...life is easy. Something like this

var mygroups = svg.selectAll("g")
    .data(piedata)
    .enter().append("g");
mygroups
    .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);
})
    .attr("class", "rectangle")
    .style("fill", function (d) {
    return color(d.label);
});
mygroups
    .append("svg:image")
    .attr("xlink:href",function(d) {return d.image})
    .attr("height", function (d) {
    return y(d.y0) - y(d.y1);
}).attr("width", x.rangeBand())
    .attr("y", function (d) {
    return y(d.y1);
});

Working code here: http://jsfiddle.net/cyril123/0xo38x8q/7/