美文网首页
D3之图表中的legend

D3之图表中的legend

作者: 桃桃 | 来源:发表于2014-11-03 14:30 被阅读0次

一、group的应用

group可以理解为div、它常常用在对一个大型的图表分模块。例如:对于一个图表,它可能有:图表主题、图标的解释说明、图标的legend、图标的axis。那么每个模块我们可以认为是一个组,用group包裹起来。

二、color的应用

var colors = d3.scale.category10() //定义一个有10种颜色的函数,通过color(i)取得每个颜色值

三、制作legend

3.1 分解legend

一个legend可以分解为:绘制不同颜色的rect、绘制每项对应的文字描述

3.2分析如何实现

对于legend是一个group,由于legend的每一项包含rect、text.因此legend的每项也是一个group

3.3 legend中的难点

对于legend有一个重点,legend中的每一项的文字长度有可能是不一样的,那么我们在制作legend时,一定要根据具体的字数计算该移动多少。

四、代码实现

4.1 数据初始化

var self = this,
    data = ['这个那个这个',20,30],
    newData = [],
    width = 0,
    rectWidth = 25,
    rectPadding = 5, 
    rectHeight = 18,
    gMargin = 15;
this.fontSize = '12px';
Talent.$.each(data,function(index,item){
                var obj = {}
                obj.value = item
                obj.width = width;
                width = width + self.calculateWidth(item)+rectWidth+rectPadding+gMargin;
                newData.push(obj);
})//这里我用了jQuery的each

其中最后的处理数据是最关键的
4.2 绘制每个group

var lableGrops = svg.selectAll('.lableGroup').selectAll('g')
                    .data(newData)
                    .enter()
                    .append('g') 
                    .attr({
                        'transform':function(d,i){
                            var x = d.width;
                            return 'translate('+[x,rectHeight/2]+')'
                        }
                    })

其中计算每个分组应该移动的的距离最关键
4.3 绘制rect和text

lableGrops.append('rect')
          .attr({
                 'width':rectWidth
                ,'height':rectHeight
                ,'x':0
                ,y:-(rectHeight/2)
                ,'rx':5
                ,'ry':5
                ,fill:function(d,i){
                      return color(i);
                 }
           })
lableGrops.append('text')
          .attr({
                 x:rectWidth+rectPadding
               ,'alignment-baseline':'middle'
               ,fill:'black'
          })
         .text(function(d,i){
                    return d.value;
          })
         .style({
                   'font-size':self.fontSize
          })

注意的要点:
在group中,我们绘制的一切都是以group来计算的。这样一来我们只管绘制group中的东西,最后关心group何如显示就可以。
4.4 计算width

calculateWidth:function(text){
    var self =  this;
    var sensor = Talent.$('<pre>' + text + '</pre>').css({
                 'display': 'none'
                   ,'font-size':self.fontSize
    });
    Talent.$('body').append(sensor);
    var width = sensor.width();
    sensor.remove();
    return width;
}

五、看图

QQ图片20141103143901.jpg

相关文章

网友评论

      本文标题:D3之图表中的legend

      本文链接:https://www.haomeiwen.com/subject/hyyltttx.html