Jay
Jay

Reputation: 747

How to make a color gradient bar using d3js

I'm trying to implement a a gradient bar using d3js, so by giving 2 colours I need to show the gradient colour starting from the first colour value and ending with the other colour value.

So it would look similar to this:

vertical gradient bar with numbers down the right hand side

This is the legend for a scatterplot chart I'm implementing using hexagonal bins, where bins color indicates the frequency on each point. Since I'm building the data dynamically, I need to append this into another dynamically built SVG.

Upvotes: 2

Views: 11751

Answers (2)

ksav
ksav

Reputation: 20821

You can create a gradient in your svg defs and then apply it to any svg shape.

    <svg width="800" height="600" version="1.1" xmlns="http://www.w3.org/2000/svg">
      <defs>
          <linearGradient id="Gradient2" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stop-color="red"/>
            <stop offset="100%" stop-color="yellow"/>
          </linearGradient>
      </defs>

      <rect x="10" y="120"  width="15" height="100" fill="url(#Gradient2)"/>
      
    </svg>

Fiddle: https://jsfiddle.net/gejuxmdx/1/

Edit: You can hardcode this as plain SVG or create it with D3 as you would any other SVG.

Edit2: To do the same thing with d3

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

var defs = svgSelect.append('defs');

var lg = defs.append('linearGradient')
 .attr('id', 'Gradient2')
 .attr('x1', 0)
 .attr('x2', 0)
 .attr('y1', 0)
 .attr('y2', 1);

lg.append('stop')
 .attr('offset', '0%')
 .attr('stop-color', 'red');

lg.append('stop')
 .attr('offset', '100%')
 .attr('stop-color', 'yellow');


svgSelect.append('rect')
 .attr('x', 10)
 .attr('y', 120)
 .attr('width', 20)
 .attr('height', 120)
 .style("fill", "url(#Gradient2)");
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Upvotes: 5

Mark
Mark

Reputation: 108512

Here's some working d3 code.

Adjusting the colors array makes the code data-driven!

var colors = [ 'rgb(255,0,0)', 'rgb(255,255,0)' ];

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

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

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

svg.append('rect')
  .attr('x', 10)
  .attr('y', 10)
  .attr('width', 50)
  .attr('height', 150)
  .style('fill', 'url(#grad)');


          
          
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Upvotes: 8

Related Questions