31,19 €
D3.js is a visualization library used for the creation and control of dynamic and interactive graphical forms. It is a library used to manipulate HTML and SVG documents as well as the Canvas element based on data. Using D3.js, developers can create interactive maps for the web, that look and feel beautiful.
This book will show you how build and design maps with D3.js and gives you great insight into projections, colors, and the most appropriate types of map.
The book begins by helping you set up all the tools necessary to build visualizations and maps. Then it covers obtaining geographic data, modifying it to your specific needs, visualizing it with augmented data using D3.js. It will further show you how to draw and map with the Canvas API and how to publish your visualization. By the end of this book, you'll be creating maps like the election maps and the kind of infographics you'll find on sites like the New York Times.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 274
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: December 2014
Second edition: November 2017
Production reference: 2050618
ISBN: 978-1-78728-017-5
www.packtpub.com
AuthorsThomas Newton Oscar VillarrealLars Verspohl
Copy EditorSafis Editing
Reviewers
Andrew Reid Xun (Brian) Wu
Project Coordinator
Sheejal Shah
Commissioning Editor
Ashwin Nair
Proofreader
Safis Editing
Acquisition Editor
Nitin Dasan
Indexer
Rekha Nair
Content Development Editor
Sreeja Nair
Graphics
Jason Monteiro
Technical Editor Leena Patil
Production Coordinator
Arvindkumar Gupta
Thomas Newton has over 20 years of experience in software engineering, creating highly scalable and flexible software solutions for clients. During this period, he has developed a broad range of expertise ranging from data visualizations, to large-scale cloud platforms, to continuous delivery and DevOps. When not going in a new technology, he spends time with his beautiful family.
Oscar Villarreal has been building web applications and visualizations for the past 15 years. He's worked with all kinds of businesses and organizations globally, helping them visualize and interact with data in more meaningful ways. He enjoys spending time with his wife and kid, as well as hanging from the edge of a rock wall when climbing.
Lars Verspohlhas been modeling and visualizing data for over 15 years. He works with businesses and organisations from all over the world to turn their often complex data into intelligible interactive visualizations. He also writes and builds stuff at datamake.io. His ideal weekend is spent either at a lake or on a mountain with his kids, although it can be hard to tear them away from the computer games he wrote for them.
Andrew Reid is a GIS specialist, despite an initial academic focus in the humanities, living and working in the Yukon Territory, Canada. Andrew has been exploring the world of D3 for several years, especially in relation to its geographic capacities. While he spends a disproportionate amount of time programming and working with geographic data in the long northern winter, Andrew makes full use of the summer's midnight sun, exploring and enjoying the northern wilderness.
Xun (Brian) Wu has more than 15 years of experience in web/mobile development, big data analytics, cloud computing, blockchain, and IT architecture. Xun holds a master's degree in computer science from NJIT. He is always enthusiastic about exploring new ideas, technologies, and opportunities that arise. He always keeps himself up to date by coding, reading books, and researching. He has previously reviewed more than 40 Packt Publishing books.
For support files and downloads related to your book, please visitwww.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version atwww.PacktPub.comand as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us [email protected] more details.
Atwww.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt</li>
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787280179.
If you'd like to join our team of regular reviewers, you can e-mail us [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Title Page
Second Edition
Copyright
Learning D3.js 5 Mapping
Second Edition
Credits
Foreword
About the Authors
About the Reviewers
www.PacktPub.com
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Gathering Your Cartography Toolbox
Quick bootstrap
Step-by-step bootstrap
A lightweight web server
Using the web browser as a development tool
Installing the sample code
Working with the developer tools
Summary
Creating Images from Simple Text
The SVG coordinate system
Line
Rectangle
Circle
Polygon
Path
Experiment
Paths with curves
Transform
Translate
Scale
Grouping
Text
Summary
Producing Graphics from Data - the Foundations of D3
Creating basic SVG elements
The enter() function
The update function
The exit() function
Fetch
Summary
Creating a Map
Foundation - creating your basic map
Including the dataset
Experiment 1 – adjusting the bounding box
Experiment 2 – creating choropleths
Experiment 3 – adding click events to our visualization
Experiment 4 – using updates and transitions to enhance our visualization
Experiment 5 – adding points of interest
Experiment 6 – adding visualizations as a point of interest
Summary
Click-Click Boom! Applying Interactivity to Your Map
Events and how they occur
Experiment 1 – hover events and tooltips
Experiment 2 – tooltips with visualizations
Experiment 3 – panning and zooming
Experiment 4 – orthographic projections
Experiment 5 – rotating orthographic projections
Experiment 6 – dragging orthographic projections
Summary
Finding and Working with Geographic Data
Geodata file types
What are shapefiles and how do I get them?
Acquiring shapefiles for a specific country
GeoJSON
A quick map in D3 with only GeoJSON
TopoJSON basics
TopoJSON command-line tips
Simplification
Merging files
Summary
Testing
Code organization and reusable assets
Project structure
Exploring the code directory
Other administrative files
Writing testable code
Keeping methods/functions small
Preventing side effects
An example with viz.js
Unit testing
Creating resilient visualization code
Adding a new test case
Summary
Drawing with Canvas and D3
Introducing Canvas
Drawing with Canvas
The three drawing steps of every Canvas visual
Drawing various shapes with Canvas
Animating the Canvas
Animating the Canvas way
Getting a general overview
Preparing the rain data
Updating each drop
Drawing frame by frame
Canvas and D3
Getting an overview of our experiment
The data
Updating each drop
Binding the data
Drawing the data
Running the app
Summary
Mapping with Canvas and D3
Choosing Canvas or SVG
Reasons to choose SVG
Reasons to choose Canvas
Visualizing flight paths with Canvas and D3
The data
Building the flight path map in SVG
Measuring the performance
Building the flight path map in Canvas
Setting up the map
Drawing the map and listening for user input
Preparing and drawing with Canvas
Drawing the background scene
Defining the planes
Calculating the plane's positions
Animating the plane
Measuring the performance
Optimizing performance
Continuing with measuring performance
Summary
Adding Interactivity to Your Canvas Map
Why Canvas interaction is different
Drawing the world on a Canvas
Setting up
Drawing the world
Making the world move
Setting up the behavior
Handling zoom and rotation
Finding the Canvas object under the mouse - Picking
Picking, the theory
Creating all things hidden
Drawing the hidden Canvas
Picking the values
Storing more data and using a lookup array
Highlighting the country on mouse over
Visualizing data per country and adding a tooltip
Adding new data to our old globe
Coloring the globe
Adding a tooltip
The HTML
Building the static parts of the tooltip
Showing and hiding the tooltip
Summary
Shaping Maps with Data - Hexbin Maps
Reviewing map visualization techniques
Choropleth maps
Cartograms
Dot density maps
Value and use of the hexagon
Making a hexbin map
Reviewing the hexbin algorithm
Setting it up
Drawing the map
Drawing a point grid for our hexagons
Keeping only the points within the map
Making the hex tile
Retrieving the hexagon center points
Drawing the hex tiles
Joining data points to the layout points
Dressing our data for the final act
Turning our visual into an interactive app
Adding additional information on hover and click
Changing the hexagon size
Changing the color scale interpolator
Browsing different datasets
Encoding data as hexagon size
Summary
Publishing Your Visualization with GitHub Pages
What we will publish
Understanding the type of content you can publish
Hosting your code on GitHub
Making sense of some key terms and concepts
Tracking historic changes of your files
Collaborating on a project
Working on project branches
Setting up a GitHub account
Creating a repository
Editing a file on GitHub
Uploading files to the repository
Publishing your project on GitHub Pages
Preparing the files for publishing
Keeping your paths absolute
Changing the main HTML filename to index.html
Publishing your project
Summary
This book explores the JavaScript library D3. js and its ability to help us create maps and amazing visualizations. You will no longer be confined to third-party tools in order to get a nice looking map. With D3. js, you can build your own maps and customize them as you please. This book will go from the basics of SVG, Canvas, and JavaScript, through to data trimming and modification with TopoJSON. Using D3. js to glue together these key ingredients, we will create very attractive maps that cover many common use cases, such as choropleths, data overlays on maps, interactivity, and performance.
Chapter 1, Gathering Your Cartography Toolbox, starts off with a working example in order to get a feel for what you will be able to build by the end of the book.
Chapter 2, Creating Images from Simple Text, dives into SVG and its common geographic shapes and attributes. Showcases how one can animate with vectors.
Chapter 3, Producing Graphics from Data - the Foundations of D3, reads about the foundations of the different states within D3 and how it interacts with the DOM.
Chapter 4, Creating a Map, presents our first examples of building maps. The chapter covers basic events and extending past map borders, as we intertwine the map with other data sets.
Chapter 5, Click-Click Boom! Applying Interactivity to Your Map, dives into all the types of interactions you can have with a map in your browser. This includes hovering, panning, zooming, and so on.
Chapter 6, Finding and Working with Geographic Data, shows how to find and utilize geospatial data.
Chapter 7, Testing, describes how to structure your codebase in order to have reusable chart components that are easily unit tested and primed for reuse in future projects.
Chapter 8, Drawing with Canvas and D3, shows how to get started with Canvas. You'll learn to draw, animate, and use the D3 life cycle for data updates.
Chapter 9, Mapping with Canvasand D3, describes how to map and animate thousands of points with Canvas, as well as how Canvas animation compares to SVG animation.
Chapter 10, Adding Interactivity to Your Canvas Map, guides you through the process of adding interactivity to Canvas, a process that requires a little more thought and attention than with SVG.
Chapter 11, Shaping Maps with Data – Hexbin Maps, explains how to build hexbin maps with D3 - a great way to show geospatial point data.
Chapter 12, Publishing a Visualization with GitHub Pages, shows you how to get your visualization online in a simple and fast way.
The following are the requirements for this book; these work on macOS, Windows, and Linux:
A D3.js library v5.0.0
Node.js
v8.9.0+
npm
for example, v5.5.1+
This book is for people with at least a basic knowledge of web development (basic HTML/CSS/JavaScript). You don't need to have worked with D3.js before.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The width and height are the only properties the canvas element has."
A block of code is set as follows:
context.save();context.translate(140, 190);context.fillRect(0, 0, 60, 30);context.restore();
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "You go to https://github.com/, click on Sign in, and follow the steps."
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learning-D3js-4-Mapping-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/LearningD3dotjs4MappingSecondEdition_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/supportand enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Welcome to the world of cartography with D3. In this chapter, you will be given all the tools you need to create a map using D3. These tools exist freely and openly, thanks to the wonderful world of open source. Given that we are going to be speaking in terms of the web, our languages will be HTML, CSS, and JavaScript. After reading this book, you will be able to use all three languages effectively in order to create maps on your own.
In this chapter, we will cover the following topics:
Quick bootstrap
Step-by-step bootstrap
Installing key libraries and tools
Using the web browser as a development tool
When creating maps in D3, your toolbox is extraordinarily light. The goal is to focus on creating data visualizations and remove the burden of heavy IDEs and map-making software.
The following instructions assume that Node.js , npm, andgitare already installed on your system. If not, feel free to follow the Step-by-Step bootstrap section.
Type the following in the command line to install a light webserver::
npm install -g http-server
Install TopoJSON:
npm install -g topojson
Clone the sample code with included libraries:
git clone --depth=1 https://github.com/PacktPublishing/Learning-D3js-4-Mapping-Second-Edition.git
Go to the root project:
cd d3jsMaps
To start the server type the following:
http-server
Now, open your web browser to http://localhost:8080/chapter-1/example-1.html, and you should see the following map:
The next section covers detailed instructions to set up your development environment if you do not have any of the required packages. By the end of the chapter, you will have a working environment for the rest of the book (an example of a running map and an initial look at tools used to create visualizations).
Technically, most of the content we will craft can render directly in the browser without the use of a web server. However, we highly recommend you do not go ahead with this approach. Running a web server in your local development environment is extremely easy and provides several benefits:
Geographic information, statistical data, and visualization code can be clearly separated into isolated files
API calls can be stubbed and simulated, allowing easy integration into a full-stack application in the future
It will prevent common mistakes when making
Fetch
calls to fetch geographic and statistical data (for example, the same-origin policy)
For our choice of web server and other tools in our toolbox, we will rely on a Node.js package named http-server. Node.js is a platform built on Chrome's JavaScript runtime, which is used to build fast, scalable network applications. The platform includes Node Package Manager (npm), which was created by other members of the vibrant Node.js community and allows the developer to quickly install packages of pre-built software.
To install Node.js, simply perform the following steps:
Go to the website
http://nodejs.org
.
Click on the
INSTALL
button.
Open the downloaded package and follow the defaults.
To test the installation, type the following in the command line:
node -v
Something similar should return:
v0.10.26
This means we have installed the given version of Node.js.
TopoJSON is a command-line utility used to create files in the TopoJSON-serialized format. The TopoJSON format will be discussed in detail in Chapter 6, Finding and Working with Geographic Data. The TopoJSON utility is also installed via npm.
We have already installed Node.js and npm, so enter the following on the command line:
npm install -g topojson
npm install –g shapefile
Once the installation is complete, you should check the version of TopoJSON installed on your machine just as we did with Node.js:
geo2topo --version
If you see version 3.x, it means you have successfully installed TopoJSON.
If you're using Windows, the basic steps to get TopoJSON working are as follows:
Install Python 2.x (3.x not supported at the time of writing this book).
Install Microsoft Visual Studio C++ 2012 for Desktop (Express).
Although any modern browser supports Scalable Vector Graphics (SVG) and has some kind of console, we strongly recommend you use Google Chrome for these examples. It comes bundled with developer tools that will allow you to very easily open, explore, and modify the code. If you are not using Google Chrome, please go to http://www.google.com/chrome and install Google Chrome.
Go to https://github.com/climboid/d3jsMaps and either clone the repo, if you are familiar with Git cloning, or simply download the zipped version. Once it is downloaded, make sure to extract the file if you have it zipped.
Use the command prompt or terminal to go to the directory where you downloaded your file. For instance, if you downloaded the file to your desktop, type in the following:
cd ~/Desktop/d3jsMaps
To start the server type the following:
http-server
The last command will launch the simple server we installed previously for the supplied sample code. This means that, if you open your browser and go to http://localhost:8080/chapter-1/example-1.html, you should see a map of Europe, similar to the one shown earlier.
It's time to open the developer tools. In the top-right corner of the browser, you will see the icon as shown in the following screenshot:
This icon opens a submenu. Click on MoreTools, then click on Developer tools. A panel will open at the bottom of the browser, containing all the developer tools at your disposal.
Within developer tools, you have a series of tabs (Elements, Network, Sources, and so on). These tools are extremely valuable and will allow you to inspect different aspects of your code. For more information on the Chrome developer tools, please go to this link: https://developer.chrome.com/devtools/docs/authoring-development-workflow.
Since we are going to focus on the Elements tab, click on it if it is not already selected.
You should see something similar to the preceding screenshot; it will have the following code statement:
<svg width="812" height="584">
If you click on the SVG item, you should see it expand and display the path tag. The path tag will have several numbers and characters tied to a d attribute. These numbers are control points that draw the path. We will cover how the path is drawn in the next chapter and how path tags are used to create maps in Chapter 4,Creating a Map and Chapter 5,Click-Click Boom! Applying Interactivity to Your Map.
We also want to draw your attention to how the HTML5 application loads the D3 library. Again, in the Elements tag, after the SVG tag, you should see the <script> tag pointing to D3.js and TopoJSON:
<script src="http://d3js.org/d3.v5.min.js" charset="utf-8"></script> <script src="https://unpkg.com/[email protected]/dist/topojson.js"></script>
If you click on the path located inside the SVG tag, you will see a new panel called the CSS inspector or the styles inspector. It shows and controls all the styles that are applied to a selected element, in this case, the path element.
These three components create a D3 visualization:
HTML5 (the SVG and path elements)
JavaScript (the D3.js library and map code)
CSS (the styling of the HTML5 elements)
Creating maps and visualizations using these three components will be discussed and analyzed throughout the book.
This chapter reveals a quick glimpse of the steps for basic setup in order to have a well-organized codebase to create maps with D3. You should become familiar with this setup because we will be using this convention throughout the book.
The remaining chapters will focus on creating detailed maps and achieving realistic visualizations through HTML, JavaScript, and CSS.
Let's go!
In this chapter, a high-level overview of Scalable Vector Graphics (SVG) will be presented by explaining how it operates and what elements it encompasses. In a browser context, SVG is very similar to HTML and is one of the means by which D3 expresses its power. Understanding the nodes and attributes of SVG will empower us to create many kinds of visualizations, not just maps. This chapter includes the following points:
A general overview of SVG and its key elements
The SVG coordinate system
The primary elements of SVG (lines, rectangles, circles, polygons, and paths)
SVG, an XML markup language, is designed to describe two-dimensional vector graphics. The SVG markup language resides in the DOM as a node that describes exactly how to draw a shape (a curve, line, circle, or polygon). Just like HTML, SVG tags can also be styled from standard CSS. Note that, because all commands reside in the DOM, the more shapes you have, the more nodes you have and the more work for the browser. This is important to remember because, as SVG visualizations become more complex, the less fluidly they will perform.
The main SVG node is declared as follows:
<svg width="200" height="200"></svg>
This node's basic properties are width and height; they provide the primary container for the other nodes that make up a visualization. For example, if you wanted to create 10 sequential circles in a 200 x 200 box, the tags would look like this:
<?xml version="1.0"?> <svg width="200" height="200"> <circle cx="60" cy="60" r="50"/> <circle cx ="5" cy="5" r="10"/> <circle cx="25" cy="35" r="45"/> <circle cx="180" cy="180" r="10"/> <circle cx="80" cy="130" r="40"/> <circle cx="50" cy="50" r="5"/> <circle cx="2" cy="2" r="7"/> <circle cx="77" cy="77" r="17"/> <circle cx="100" cy="100" r="40"/> <circle cx="146" cy="109" r="22"/> </svg>
Note that 10 circles would need 10 nodes in the DOM, plus its container.
SVG contains several primitives that allow the developer to draw shapes quickly. We will cover the following primitives throughout this chapter:
circle
: A standard circle with a defined radius and position attributes
rect
: A standard rectangle with height, width, and position attributes
polygon
: Any polygon, described by a list of points
line
: A line with start and end points
path
: A complex line created through a series of drawing commands
What about position? Where do these primitives draw inside the SVG element? What if you wanted to put a circle in the top-left and another one bottom-right? Where do you start?
SVG is positioned by a grid system, similar to the Cartesian coordinate system. However, in SVG (0,0) is the top-left corner. The x axis proceeds horizontally from left to right starting at 0. The y axis also starts at 0 and extends downward. See the following illustration:
What about drawing shapes on top of each other? How do you control the z index? In SVG, there is no z coordinate. Depth is determined by the order in which the shape is drawn. If you were to draw a circle with coordinates (10,10) and then another one with coordinates (10,10), you would see the second circle drawn on top of the first.
The following sections will cover the basic SVG primitives for drawing shapes and some of their most common attributes.
The SVG line is one of the simplest in the library. It draws a straight line from one point to another. The syntax is very straightforward and can be experimented with at: http://localhost:8080/chapter-2/line.html, assuming the HTTP server is running:
<line x1="10" y1="10" x2="100" y2="100" stroke-width="1" stroke="red"/>
This will give you the following output:
A description of the element's attributes is as follows:
x1
and
y1
: The starting
x
and
y
coordinates
x2
and
y2
: The ending
x
and
y
coordinates
stroke
: This gives the line a red color
stroke-width
: This denotes the width of the line to be drawn in pixels
The line tag also has the ability to change the style of the end of the line. For example, adding the following would change the image so it has round ends:
stroke-linecap: round;
As stated earlier, all SVG tags can also be styled with CSS elements. An alternative way of producing the same graphic would be to first create a CSS style, as shown in the following code:
line { stroke: red; stroke-linecap: round; stroke-width: 5; }
Then you can create a very simple SVG tag using the following code:
<line x1="10" y1="10" x2="100" y2="100"></line>
More complex lines, as well as curves, can be achieved with the path tag; we will cover it in the Path section.