如何使用d3.js创建水平图例 [英] How to create a horizontal legend with d3.js

查看:305
本文介绍了如何使用d3.js创建水平图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用d3.js为我的图形创建一个水平图例。我尝试使用动态标签获得正确的x轴间距。

I've been trying to create a horizontal legend for my graph using d3.js. I've struggled to get the x-axis spacing correct with dynamic labels.

问题是标签的宽度不一致,这里是一个 full example ,这是我计算x位置的函数:

The problem is that the labels are not of a consistent width, here's a full example and this is my function to calculate the x position:

function legendXPosition(data, position, avgFontWidth){
    if(position == 0){
        return 0;
    } else {
        var xPostiion = 0;
        for(i = 0; i < position; i++){
            xPostiion += (data[i].length * avgFontWidth);
        }
        return xPostiion;
    }
}

有没有人对如何改善这个有任何建议?

Does anyone have any suggestions on how to improve this?

推荐答案

我建议引用此问题: svg文本元素宽度

像您一样呈现第一个图例条目。

Render the first legend entry as you already are. Store this entry, or assign ids such that you can look them up through selection.

在绘制后续条目时,获取上一个text元素和x偏移量。使用上一个文本元素的精确宽度计算新的图例条目偏移

When rendering subsequent entries, get the previous 'text' element and x offset. Compute the new legend entry offset using the exact width of the previous text element

var myNewXOffset = myPreviousXOffset + myPreviousText.getBBox().width

这篇关于如何使用d3.js创建水平图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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