简体   繁体   中英

legend placement issue in D3 Bar chart

I have a stacked bar chart. I want to place the legend, just above the chart area ends and in centre like this 传说

I have created a Fiddle Here Legend Fiddle

But I am facing issue in locating the legend at correct position so that it works on IPAD as well. I know some issue in

.attr("transform", function(d, i) { return "translate(-180," + i * 20 + ")"; });

Could you please help in placing legend at right location. Thanks Gunjan

If you want this to display properly on mobile devices you should probably replace most of the static element sizing with dynamic viewport queries. However getting the legend to display properly doesn't explicitly require this.

I added 10px to the top margin:

var margin = {top: 30, right: 20, bottom: 30, left: 40},

Then I changed the transform applied to the legend element

       .attr("transform", function(d, i) { return "translate("+ ((i * 50) + (width/2)-25)  +"," + (-margin.top) + ")"; });

I also had to remove the "x" attributes on the rect and text elements. It gets confusing when you are trying to position an element in two different places so removing it here lets you concentrate on positioning it correctly with the group transform.

      legend.append("rect")
    .attr("width", 18)
    .attr("height", 18)
    .style("fill", color);
  legend.append("text")
    .attr("dx", -4)
    .attr("dy", ".8em")
    .style("text-anchor", "end")
    .text(function(d) { return d; });

http://jsfiddle.net/QDVUc/1/

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