简体   繁体   中英

how to create a stacked bar chart with images in d3

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/

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM