How to shade area between 2 lines using d3.js?

by herminia_bruen , in category: Javascript , 6 months ago

How to shade area between 2 lines using d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 6 months ago

@herminia_bruen 

To shade the area between two lines using d3.js, you can use the d3.area() function along with the d3.svg.area() function to create a path representing the area to be shaded.


Here's a step-by-step guide on how to shade the area between two lines using d3.js:

  1. First, create an SVG element in your HTML document where you want to display the shaded area:
1
<svg width="800" height="400"></svg>


  1. Then, define your dataset containing the points for the two lines:
1
2
3
4
5
6
var data = [
  {x: 0, y1: 50, y2: 100},
  {x: 50, y1: 70, y2: 120},
  {x: 100, y1: 90, y2: 140},
  // Add more data points as needed
];


  1. Create scales for the x and y axes:
1
2
3
4
5
6
7
var xScale = d3.scaleLinear()
  .domain([0, 100])
  .range([0, 800]);

var yScale = d3.scaleLinear()
  .domain([0, 150])
  .range([400, 0]);


  1. Create line generators for the two lines:
1
2
3
4
5
6
7
var line1 = d3.line()
  .x(function(d) { return xScale(d.x); })
  .y(function(d) { return yScale(d.y1); });

var line2 = d3.line()
  .x(function(d) { return xScale(d.x); })
  .y(function(d) { return yScale(d.y2); });


  1. Create an area generator for the shaded area between the two lines:
1
2
3
4
var area = d3.area()
  .x(function(d) { return xScale(d.x); })
  .y0(function(d) { return yScale(d.y1); })
  .y1(function(d) { return yScale(d.y2); });


  1. Append the two lines and the shaded area to the SVG element:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var svg = d3.select('svg');

svg.append('path')
  .datum(data)
  .attr('fill', 'lightblue')
  .attr('d', area);

svg.append('path')
  .datum(data)
  .attr('stroke', 'blue')
  .attr('d', line1);

svg.append('path')
  .datum(data)
  .attr('stroke', 'green')
  .attr('d', line2);


With these steps, you should now see the shaded area between the two lines displayed on your SVG element. You can customize the colors, line styles, and other attributes as needed to achieve the desired effect.