We will first draw a simple line using D3 and then modify some its properties such as width and opacity. Note that we are actually using the D3.js to generate SVG code for drawing the line. If you don't know what SVG is, don't worry. We will pick it up as we go along.
Create the basic HTML file that will contain the code. Note the DIV container with id = "D3line" . We will add the line to this DIV container. Also, see the header of the file. We have linked to the D3 repository to load the D3.js script. You will need to be connected to the internet for the following to work.
Now add the following D3 script after the <div id="D3line"></div> line. Here we select the DIV container D3line, add an SVG element to it, and set its height and width attributes. We assign the SVG element to a variable that we name lineGraph.
Now add the SVG line element to the SVG element that we added above, by adding the following script after the .attr("height", 400); line. As you can see, you need to specify four attributes to add a line: x and y coordinates of the starting point, (x1,y1), and end point x and y coordinates (x2, y2). Further, you need to specify the color for the line, which is value of the stroke element.
// To draw a line use the "svg:line" element. // "svg:line" element requires 4 attributes (x1, y1, x2, and y2) // (x1,y1) are coordinates of the starting point. // (x2,y2) are coordinates of the end point. // You also need to specify the stroke color. var myLine = lineGraph.append("svg:line") .attr("x1", 40) .attr("y1", 50) .attr("x2", 450) .attr("y2", 150) .style("stroke", "rgb(6,120,155)");Open the HTML file that you have so far in the browser and you should see a line such as in the following figure. Note that the origin in SVG is at the top left hand corner.
There, you are done! Before I wrap up this post, I will show how to change a couple of properties of this line. We will first increase the thickness of the line (using the stroke-width property) and then make it a little transparent (reduce its opacity) using the stroke-opacity property.
To increase the line width add:
This gives: Finally, to make the line transparent add the following lines to the script.
// Increase the line thickness/width myLine.style("stroke-width", 24);
// Make the line a little transparent (decrease opacity) myLine.style("stroke-opacity", 0.6);This gives: