如何在 D3 图表的标签中包含换行符? [英] How do I include newlines in labels in D3 charts?

查看:39
本文介绍了如何在 D3 图表的标签中包含换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 D3 生成条形图(我改编了本示例中的代码).我在 x 轴上使用的标签每个都有几个字长,因为这会使所有标签重叠,所以我需要将这些标签跨行分开.(如果我可以用换行符替换每个标签中的所有空格就好了.)

I'm using D3 to generate a bar chart (I adapted the code from this example). The labels I'm using on the x-axis are a couple of words long each, and since this makes all of the labels overlap I need to break these labels across lines. (It'll be fine if I can replace all of the spaces in each label with newlines.)

我最初尝试通过用文字换行符 (&#xA;) 替换空格并在标签的 上设置 xml:space="preserve"> 元素.不幸的是,事实证明 SVG 不尊重这个属性.接下来,我尝试用 <tspan> 包装每个单词,以便我以后可以设置样式.我通过这个函数传递了每个标签:

I originally tried this by replacing the spaces with literal newlines (&#xA;) and setting xml:space="preserve" on the labels' <text> elements. Unfortunately, it turns out that SVG doesn't respect this property. Next I tried to wrap each word in a <tspan> that I could later style. I passed each label through this function:

function (text) {
    return '<tspan>' + text.replace(/ /g, '</tspan><tspan>') + '</tspan>';
}

但这只是将文字 s 放入输出中.如何将我的文本标签包裹在 tspan 中(或执行其他操作),以便我的标签不重叠?

but this just puts literal <tspan>s into the output. How can I wrap my text labels in tspans (or do something else) so that my labels don't overlap?

推荐答案

我最终使用以下代码将每个 x 轴标签分成几行:

I ended up using the following code to break each x-axis label across lines:

var insertLinebreaks = function (d) {
    var el = d3.select(this);
    var words = d.split(' ');
    el.text('');

    for (var i = 0; i < words.length; i++) {
        var tspan = el.append('tspan').text(words[i]);
        if (i > 0)
            tspan.attr('x', 0).attr('dy', '15');
    }
};

svg.selectAll('g.x.axis g text').each(insertLinebreaks);

请注意,这假定标签已经创建.(如果您遵循规范直方图示例,那么标签将按照您需要的方式设置.)也没有't 存在任何真正的断行逻辑;该函数将每个空格转换为换行符.这很符合我的目的,但您可能需要编辑 split() 行,以便更智能地了解它如何将字符串的各个部分分成几行.

Note that this assumes that the labels have already been created. (If you follow the canonical histogram example then the labels will have been set up in just the way you need.) There also isn't any real line-breaking logic present; the function converts every space into a newline. This fits my purposes fine but you may need to edit the split() line to be smarter about how it partitions the parts of the string into lines.

这篇关于如何在 D3 图表的标签中包含换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆