簡體   English   中英

在D3圖表中使用SVG組作為更復雜的條形圖

[英]Use SVG groups as more complex version of bars in D3 charts

假設我有一些使用D3構建的復雜數據可視化。 我想不僅添加不同大小的基本組,而是創建由不同圖形組構建的單元集,例如在單個組元素中具有一些矩形,三角形指針,文本標簽和背景矩形。

主要是我運行var unit = d3.select('.unit').data(units).enter().append('g')來創建這些容器。 現在我如何正確添加內部內容,以便它不會使用簡單的unit.append('rect')在每次數據更新時添加多個欺騙項?

現在我必須做這樣的事情if (!unit.select('.label').size()){//append the element} else {//update existing element}

如果我已經如單元內5元,很容易變得很丑陋所有這些if..then

有沒有更好的方法來管理這樣的案件?

您可以將復雜的圖形移動到單獨的功能

var unit = d3.selectAll('.unit').data(units);

// ENTER
unit.enter().append('g')
    .attr('class', 'unit')
    // ... transform and other unit-level stuff here

// UPDATE
unit.transition().duration()
    .call(drawUnit);

// EXIT
unit.exit()
    .remove();

drawUnit函數中,您可以編寫如下內容:

function drawUnit(units) {
    units.each(function(d) {
        var unit = d3.select(this); // select g.unit
        // DRAW LABEL
        var label = unit.selectAll('text')
            .data([d]); // rejoin data from the unit to the label

        // enter
        label.enter()
            .append('text');

        // update
        label
            .text(function(d) { return d.label; });

        // exit
        // if you need to hide the labels then instead of `.data([d])` you can
        // use something like this `.data(d.label.length ? [d] : [])`
        // label.exit().remove();


        // draw other inner elements of the unit
        // DRAW ARROW
        var arrow = unit.selectAll('.arrow').data([d]);
        // ....
    });
}

這是JSFiddle的更多評論: http//jsfiddle.net/fd6o4eey/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM