How to create svg with grid lines using d3.js?

Member

by addison , in category: Javascript , 9 months ago

How to create svg with grid lines using d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 9 months ago

@addison 

To create an SVG with grid lines using d3.js, you can follow these steps:

  1. Import the d3.js library in your HTML file:
1
<script src="https://d3js.org/d3.v7.min.js"></script>


  1. Create an SVG element:
1
<svg width="500" height="500"></svg>


  1. Create a function to generate grid lines:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
function createGrid(svg, width, height, gridSize) {
  const xGrid = d3.axisBottom()
    .scale(d3.scaleLinear().domain([0, width]).range([0, width]))
    .ticks(width / gridSize)
    .tickSize(-height)
    .tickFormat("");

  const yGrid = d3.axisRight()
    .scale(d3.scaleLinear().domain([0, height]).range([0, height]))
    .ticks(height / gridSize)
    .tickSize(-width)
    .tickFormat("");

  svg.append("g")
    .attr("class", "x-grid")
    .call(xGrid);

  svg.append("g")
    .attr("class", "y-grid")
    .call(yGrid);
}


  1. Call the function to generate grid lines:
1
2
3
4
5
6
const svg = d3.select("svg");
const width = 500;
const height = 500;
const gridSize = 50;

createGrid(svg, width, height, gridSize);


  1. Style the grid lines using CSS:
1
2
3
4
5
6
7
.x-grid line {
  stroke: #ccc;
}

.y-grid line {
  stroke: #ccc;
}


  1. You can customize the grid lines by adjusting the width, height, and gridSize parameters in the createGrid function.


That's it! Now you should see grid lines displayed on your SVG element using d3.js.