How to create two interactive graphs with d3.js?

by jasen_gottlieb , in category: Javascript , 9 months ago

How to create two interactive graphs with d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 9 months ago

@jasen_gottlieb 

To create two interactive graphs with d3.js, you can follow these steps:

  1. First, set up your HTML file with a container for each graph:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE html>
<html>
<head>
  <title>Interactive Graphs with d3.js</title>
  <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
  <div id="graph1"></div>
  <div id="graph2"></div>

  <script src="script.js"></script>
</body>
</html>


  1. Next, create a script.js file and write the code to create the two interactive graphs:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Create data for the first graph
var data1 = [5, 10, 15, 20, 25];

// Create data for the second graph
var data2 = [30, 25, 20, 15, 10];

// Set up the dimensions for the graphs
var width = 300;
var height = 200;

// Create an SVG element for the first graph
var svg1 = d3.select("#graph1")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

// Create an SVG element for the second graph
var svg2 = d3.select("#graph2")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

// Create scales for both graphs
var xScale = d3.scaleLinear()
  .domain([0, data1.length - 1])
  .range([0, width]);

var yScale = d3.scaleLinear()
  .domain([0, d3.max(data1)])
  .range([height, 0]);

// Create the line for the first graph
var line1 = d3.line()
  .x(function(d, i) { return xScale(i); })
  .y(function(d) { return yScale(d); });

// Create the line for the second graph
var line2 = d3.line()
  .x(function(d, i) { return xScale(i); })
  .y(function(d) { return yScale(d); });

// Draw the lines for both graphs
svg1.append("path")
  .datum(data1)
  .attr("fill", "none")
  .attr("stroke", "steelblue")
  .attr("stroke-width", 2)
  .attr("d", line1);

svg2.append("path")
  .datum(data2)
  .attr("fill", "none")
  .attr("stroke", "green")
  .attr("stroke-width", 2)
  .attr("d", line2);


  1. Open the HTML file in a web browser to see your two interactive graphs.


By following these steps, you can create two interactive graphs using d3.js. You can further customize your graphs by adding axes, tooltips, and other interactive features.