【问题标题】:How to add label wrap function to NVD3 graph?如何将标签换行功能添加到 NVD3 图形?
【发布时间】:2017-05-18 08:43:31
【问题描述】:

如何将 Mike Bostock(https://bl.ocks.org/mbostock/7555321) 的标签换行功能添加到我的 nvd3 图表中?

createChart(graph_data, tickValue){
    if (graph_data) {
        var chart;

        nv.addGraph(function () {
            var chart = nv.models.multiBarChart()
                    .reduceXTicks(false)   //If 'false', every single x-axis tick label will be rendered.
                    .rotateLabels(-45)      //Angle to rotate x-axis labels.
                    .showControls(true)   //Allow user to switch between 'Grouped' and 'Stacked' mode.
                    .groupSpacing(0.15)    //Distance between each group of bars.
                ;
            chart.xAxis
                .tickFormat(function (i) {
                    return tickValue[i];
                });

            chart.yAxis
                .tickFormat(d3.format(',.1f'));

            d3.select('#chart1')
                .datum(graph_data)
                .call(chart);

            return chart;
        });
    } else {
        return <div/>
    }
}

tickValue[i] 返回字符串,例如“调用以获取详细信息、首选项和建议汽车”。

我需要包装这个字符串,以便它适合我的图表。

我尝试使用 wrap 函数 (https://bl.ocks.org/mbostock/7555321) 但无法这样做,因为它适用于 d3 而不是 nvd3。

谢谢。

【问题讨论】:

    标签: javascript reactjs d3.js nvd3.js


    【解决方案1】:

    在 nvd3 版本 1.8.5(我不知道旧版本)中,这已经实现了。只需使用

    wrapLabels: true
    

    【讨论】:

      【解决方案2】:

      这是我在问题中使用Mike Bostock’s Wrapping long labels 示例的方式。

      我使用了我在另一篇文章中回答的示例。 Here's 示例的工作版本。

      为图表添加边距以使其美观:

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

      最后,我选择了图表上的所有xAxis 刻度并将Mike Bostock’s Wrapping long labels function wrap 应用到它。将以下代码添加到图表底部。

      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);
          }
        }
      });
      

      最终输出


      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2014-12-07
        • 2015-03-23
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 1970-01-01
        • 2011-01-09
        • 2021-03-27
        • 2016-04-02
        相关资源
        最近更新 更多