Search⌘ K
AI Features

Elements: Line, Polyline, Polygon, and Path

Explore how to draw and style fundamental SVG elements in D3.js including lines, polylines, polygons, and paths. Understand the attributes needed to position these shapes and use the path mini-language to create complex outlines. This lesson helps you build foundational skills for manipulating graphical elements in interactive visualizations.

We'll cover the following...

Line

A line is a simple line between two points and is described by four required attributes.

  • x1: The x position of the first end of the line as measured from the left of the screen
  • y1: The y position of the first end of the line as measured from the top of the screen
  • x2: The x position of the second end of the line as measured from the left of the screen
  • y2: The y position of the second end of the line as measured from the top of the screen

The following is an example of the code section required to draw a line. A notable addition to this code is the style declaration. In this case, the line does not have color, and this can be added with the stroke style, which applies color to a line:

JavaScript (JSX)
holder.append("line") // attach a line
.style("stroke", "black") // colour the line
.attr("x1", 100) // x position of the first end of the line
.attr("y1", 50) // y position of the first end of the line
.attr("x2", 300) // x position of the second end of the line
.attr("y2", 150); // y position of the second end of the line

This will produce a line as follows: ...