javascript - 勾选文本/变量标签未在 d3 条形图中换行

标签 javascript d3.js data-visualization observablehq

我正在尝试将换行应用于 d3 条形图中沿 x 轴的长变量标签。这是我在 Observable 笔记本中的图表:https://observablehq.com/@unfpamaldives/figure4

我尝试应用解决方案 from this block ,主要包括以下内容:

function wrap(text, width) {
  text.each(function() {
    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(" "))
      if (tspan.node().getComputedTextLength() > width) {
        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)
      }
    }
  })
}  

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", `translate(0, ${height})`)
      .call(xAxis)
    .selectAll(".tick text")
      .call(wrap, x.bandwidth())

它看起来像什么: enter image description here
我想要实现的目标: enter image description here 我还尝试将 wrap 函数移动到代码中的其他位置(之前和之后),并尝试移动以下几行

.selectAll(".tick text")
  .call(wrap, x.bandwidth())

从该代码块中的某个位置开始工作,如下所示:

xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
  .style("font-family", "HelveticaNeueLTStd-Cn")
  .style("font-size", "9px")
.call(d3.axisBottom(x).tickSizeOuter(0))
.selectAll(".tick text")
  .call(wrap, x.bandwidth())

但是this too (尝试适应 Bostock's solution )不起作用。 (我之前已经在其他 d3 可视化中使用了文本换行,这是值得的。)任何人都可以演示基于 my Observable notebook 分支的工作解决方案吗? ?

最佳答案

我成功地对 this example 中的 x 轴条/变量标签应用了文本换行技术。来自Gerardo Furtado 。它需要以下代码:

  svg.append("g")
      .call(yAxis);

  const axis = svg.append("g")
      .call(xAxis);  

  setTimeout(()=>{
  axis.selectAll(".tick text")
      .style("font-family", "HelveticaNeueLTStd-Cn")
      .style("font-size", "9px")
    .call(wrap, x.bandwidth());
  }, 0); 

这是working solution .

关于javascript - 勾选文本/变量标签未在 d3 条形图中换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60421252/

相关文章:

javascript - jQuery函数调用后,shadowbox停止工作

javascript - 在 Meteor 中,我如何在客户端知道服务器端操作何时完成?

javascript - 导入空类时出错,错误 TS2307 : Cannot find module 'menu'

javascript - D3 图示例

Typescript/D3 v4 - d3.drag().on ("end"中的 this 上下文,this.dragended)

statistics - 可视化 - Tableau

r - 在 R : how to highlight specific areas of interest? 中抛光蜘蛛网图

javascript - 为什么没有为以下克隆数组正确设置索引?

javascript - D3圆包布局算法

python - 在 matplotlib 中绘制 3d 散点图