NVD3 Horizontal Bar Chart labels too long

前端 未结 3 2056
庸人自扰
庸人自扰 2021-01-22 20:37

I have data that has long labels, i.e:

values:
  [      
    { x : \"This is a really looong label\", y : 40 },
    { x : \"Short label\", y : 30 } 
  ]
<         


        
3条回答
  •  情深已故
    2021-01-22 21:20

    The answer might be a late but hopefully it helps. I've used Mike Bostock’s Wrapping long labels example with the question.

    Here's what I've done differently to your code.

    Added margins to the chart to make it pretty:

    var chart = nv.models.multiBarHorizontalChart().margin({
      top: 30, right: 20, bottom: 50, left: 100
    });
    

    Finally I selected all the xAxis ticks on the chart and applied Mike Bostock’s Wrapping long labels function wrap to it.

    d3.selectAll(".nv-x.nv-axis .tick text").each(function(i, e) {
      var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word, line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    
      while (word = words.pop()) {
        line.push(word);
        tspan.text(line.join(" "));
        // TDOD : Make 80 a dynamic value based on the bar width/height
        if (tspan.node().getComputedTextLength() > 80) {
          line.pop();
          tspan.text(line.join(" "));
          line = [word];
          tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
        }
      }
    });
    

    Final output

    Here's a working version of the example.

提交回复
热议问题