简体   繁体   中英

Making more space for a graph legend in d3js

The names of the legend don't fully show.They are cut off, if I increase the width, the bars just grow bigger. How can I accommodate more space for my legend?

I tried appending the legend to the 'svg' tag instead of the 'g' tag but still not the desired results. I even plotted the axis, bars and legend on the 'svg' tag but its still not working.

javascript

const g= svg.append('g')
 .attr("transform", `translate(${margin.left},${margin.top})`)

  const xAxis= g.append('g')
  .call(d3.axisBottom(x).tickSizeOuter(0))
  .attr("transform", "translate(0," + innerHeight + ")")

  const yAxis= g.append('g')
  .call(d3.axisLeft(y).tickSizeOuter(0))

  //stack the data? --> stack per subgroup
  var stackedData = d3.stack()
  .keys(subgroups)
  (data)


  var legend = g.append('g')
  .attr('class', 'legend')
  .attr('transform', `translate(${210},${20})`);

  legend.selectAll('rect')
  .data(subgroups)
  .enter()
  .append('rect')
  .attr('x', 0)
  .attr('y', function(d, i){
    return i * 20;})
  .attr('width', 14)
  .attr('height', 14)
  .attr('fill', function(d, i){
    return color(i);
});

  legend.selectAll('text')
  .data(subgroups)
  .enter()
 .append('text')
 .text(function(d){
    return d;
 })
 .attr('x',18)
 .attr('y', function(d, i){
  return i * 18;
 })
 .attr('text-anchor', 'start')
 .attr('alignment-baseline', 'hanging');


//below is my plotted data

telescope,allocated,unallocated
IRSF,61,28
1.9-m,89,0
1.0-m,64,23

// width=300 and heigh=300  for svg

I want to show the full names of the legends just next to the right of the bars for the graph.

Link to the graph is here .

How do I solve the problem?

Your issue is that the SVG's width is too narrow to accomodate showing all of the legend texts.

If your graph follows D3 conventions, space for elements that are auxilliary to graph itself (axis names, ticks, legends, etc.) is made using an margin object. Although I can't see how your graph is made, it looks like yours is setup to use a margin object as well. Following D3 conventions the margin values are fixed, which would explain why changing the width value just makes the bars wider yet still doesn't make space for the legend texts.

Therefore, locate the margin object and change its right value to something higher. Inspecting your example, it looks like doubling it should do it.

Hope this helps!

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