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

查看:325
本文介绍了如何在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.)

我最初尝试用空格替换换行符(< c $ c>标签上设置 xml:space =preserve ; text> 元素。不幸的是,事实证明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>';
}

但这只是文字< tspan> s输出。如何在 tspan s中包装我的文本标签(或做其他事情),使我的标签不重叠?

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

请注意,假设标签已创建。 (如果您按照规范直方图示例,那么标签将按照您需要的方式设置。)还有'任何真正的断线逻辑存在;该函数将每个空格转换为换行符。这符合我的目的,但你可能需要编辑 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天全站免登陆