d3.js:如何创建自定义颜色渐变图例?

时间:2015-06-20 15:38:07

标签: d3.js

我需要创建像this这样的彩虹色的图例? 但不知道该怎么做。有什么想法吗?

UPD:不幸的是,我很差劲地制定了这项任务。我不需要只带颜色的条带。我需要一个scale对象来创建图例并将其应用于填充SVG元素。

1 个答案:

答案 0 :(得分:3)

这是一个快速d3实施:

<!DOCTYPE html>
<html>

<head>
  <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
</head>

<body>
  <script>
    var data = [{
      color: 'white',
      label: 'Snow'
    }, {
      color: 'red',
      label: 'Rock'
    }, {
      color: 'purple',
      label: 'Pine'
    }, {
      color: 'blue',
      label: 'Basalt'
    }, {
      color: 'lightblue',
      label: 'Dog'
    }, {
      color: 'green',
      label: 'Cat'
    }, {
      color: 'yellow',
      label: 'Lava'
    }, {
      color: 'orange',
      label: 'Fish'
    }, {
      color: 'black',
      label: 'Sand'
    }]

    var width = 500,
      height = 150;

    var svg = d3.select('body')
      .append('svg')
      .attr('width', 500)
      .attr('height', height);

    var grad = svg.append('defs')
      .append('linearGradient')
      .attr('id', 'grad')
      .attr('x1', '0%')
      .attr('x2', '100%')
      .attr('y1', '0%')
      .attr('y2', '0%');

    grad.selectAll('stop')
      .data(data)
      .enter()
      .append('stop')
      .attr('offset', function(d, i) {
        return (i / data.length) * 100 + '%';
      })
      .style('stop-color', function(d) {
        return d.color;
      })
      .style('stop-opacity', 0.9);

    svg.append('rect')
      .attr('x', 0)
      .attr('y', 0)
      .attr('width', 500)
      .attr('height', height / 2)
      .attr('fill', 'url(#grad)');
      
    var g = svg.append('g')
      .selectAll('.label')  
      .data(data)
      .enter();
    
    g.append('line')
      .style('stroke', function(d) {
        return d.color;
      })
      .style('stroke-width', 2)
      .attr('x1',function(d,i){
        return xPos(i)
      })
      .attr('x2',function(d,i){
        return xPos(i)
      })
      .attr('y1',function(d,i){
        return height / 2;
      })
       .attr('y2',function(d,i){
        return height
      });
      
     
    g.append('text')
      .text(function(d){
        return d.label;
      })
      .attr('transform',function(d,i){
        return 'translate(' + (xPos(i) + 2) + ',' + ((height) - 7) + ')';
      })
      
    function xPos(i){
      return (width / data.length) * i;
    }
      
  </script>
</body>

</html>

Plnkr示例here

相关问题