D3.js tutorial - Learn how to use D3 for data visualizaiton

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to the d3.js course and this is the most comprehensive course on d3 around by the end of this course you will have a solid understanding of d3 and its features d3 is a JavaScript library that comes with dozens of features for creating data visualizations here is what you can expect to learn throughout this course currently you're in section 1 this section will go over some of the concepts you'll need to know throughout this course I go over what data visualization is why you should use d3 and we set up a server to get started I want to make one thing clear and this course is not about design or data science the core focus of this course is d3 and the code behind d3 data science and design principles are topics that deserve a course of their own in this course we mainly focus on the code and why you write things a certain way and this section will only give you a brief overview of things related to design and data science with that being said you are expected to know the basics of HTML CSS and JavaScript in section 2 I provide a primer on two topics I go over some JavaScript concepts that you should already know and you can consider this a refresher I just want to make sure we're all on the same page the other topic is SVG d3 is primarily used with SVG it's important to understand what SVG is and how to use it if you don't have any experience with SVG then that's perfectly fine you will learn all the basics in this section then in section 3 we'll go over the basics of d3 we won't be creating any visuals or doing anything difficult this section focuses solely on the code itself and what's happening behind the scenes afterwards in section 4 we begin actually using d3 to draw charts for this section we focus on two examples to better explain and reinforce what you learn you will learn how to create scatter plots and bar graphs more importantly you will learn about skills and how they can help us size our charts appropriately Section five will continue working with the scatterplot in bar graph will refine how it looks and begin adding interactivity this includes learning how to add change and remove data will learn about transitions and animations you also learn how to create your own custom tooltips in section 6 we begin stepping away from the charts we've created so far and start exploring other types of charts you'll learn how to use layouts and how they can help us build some of the most common types of charts out there in section 7 we'll start talking about how you would go about creating maps we won't just draw maps we'll also learn how to add interactivity such as panning and zooming by the end of this section you'll be more than comfortable drawing maps and understanding the fundamental concepts of geo JSON lastly in section 8 I go over some topics I may have missed such as responsive design in this day and age it's important that your charts are responsive for any device and there's a lot of information to go over it and so you would definitely be kept busy let's talk about the requirements now and this course assumes you have knowledge of HTML and CSS we want to use HTML and CSS too often d3 is primarily JavaScript and you can manipulate the document with it be sure you're confident in your HTML and CSS skills along with HTM on CSS you will also need to know JavaScript I'll be sure to explain some of the more advanced concepts but you should have a good understanding of the basics and this includes variables functions conditional statements arrays and objects and lastly you'll need a server and an editor of your choice if you don't have either of those then don't worry in the next lecture I'll show you how to set up your server for development and suggest an editor you can use any editor you like as long as it supports HTML CSS and JavaScript at the end of each section is a quiz and be sure to take it to test your knowledge when you're ready move on to the next lecture I'll see you there to start things off I want to start talking about the text editor we'll be using for this course you're free to use any text editor you like as long as it supports HTML CSS and JavaScript all three of these technologies play a major role in the d3 library so your editor will need to support them usually the editor I recommend for web development is Webster owned by JetBrains and there's a specific reason why I recommend this editor this is a premium editor and if you can't afford it then I provide an alternative at the end of this lecture for now let me show you why it's so useful in the resource section of this lecture I provided the power that contains a simple HTML file I want you to unzip this file anywhere in your system once you have it unzipped I want you to open it up in your browser you'll see that it's just a regular HTML document with the text saying hello if you right-click any one on the page and select new page source then you'll see a new tab open up with the original source code as I stated earlier you should have good knowledge of HTML and CSS so you should be able to understand what this code does there's nothing groundbreaking about this code if you take a look at the URL bar you'll see the full system path for HTML and CSS opening up a file like this is just fine however and later in this course your code will not work by simply opening up the files in the browser this is because we'll be learning how to load data through external sources for security reasons most browsers will not allow this unless you're on a server this forces us to set up your local server on our machines usually this is a pain to set up and setting up your server varies from language to language and luckily we won't have to mess with a single line of code related to web servers in the editor I recommend will automatically set up a server for you without having to touch a single line of code and this is great because will then be able to focus more on our code rather than the server code and let's explore how it's done if you don't have webstorm then that's fine I'll provide an alternative in just a moment just keep watching I'm going to start a web storm right now I have my HTML file opened up on the menu above I'm going to click on View this will present us with an option to open in browser you'll then see a list of browsers you can you for this course I'll be using Chrome some going to select this option and then webstorm will open up this file in the browser this may take a while for some of you since webstore boots up a server like before we have the text hello being displayed to us however what's different is the URL taking a closer look you'll see that web store opened is from something called localhost localhost refers to your computer it's telling your browser to this file that just opened up is coming from your computer and not some external server just like that without having to write a single line of code you now have a server and there's a lot more going on behind the scenes but that doesn't matter we only care about what's being displayed on the browser and that our code works we'll leave the server stuff to the server guys something I want to highlight is that this will only work for HTML documents and let me show you what I mean I'm gonna go back to my editor and I'm going to create a new file called test that j/s you don't have to follow along as this is just an example with this file opened up and appearing inside the main active editor I'm going to select the View menu item again you'll notice that the opening browser option is gone and this is because webstorm is unable to generate a server for a javascript file if you don't see the opening browser option then chances are you don't have the HTML document open up and me mean active editor this does happen from time to time so it's good to know alright so that's how you boot up a server from webstorm if you can't afford webstorm then that's perfectly fine and there's another alternative solution that doesn't require you to write a single line of code in the resource section of this lecture I provide a link to a program called xampp xampp is a program that allows you to create a server on a machine for free it comes bundled with various programs that also help with web development however you don't need to be an expert in those technologies or even know how to use them you can safely ignore those technologies if you look right below and you'll see all the installers available download the one appropriate for your system and install it just go through the default installation settings it's a normal program like anything else you just click next and continue until it's finished installing it won't be going through the installation since I already have it installed once you've installed it you can open up a program called xampp control panel it should look something like this and there are quite a few programs here but the only one you need to use is called Apache Apache will create and configure a server for you automatically all you have to do is press Start and it should boot up you may get a message saying that this program requires permission to boot up a server just say yes so xampp can do its thing Apache should turn green indicating that the program is now working if you don't see it turned green then chances are that it failed in this case you'll need to look at the slog below to see the error you'll need to message the apache french site and provide them this log so they can assist you debugging the error if your server is ready then you can press this button called admin that will open up a new tab in your browser it'll open up that localhost you saw earlier you may see you woke a message from xampp and which is fine I currently don't because I deleted those files the welcome message is something you can safely delete and ignore for this course let me show you how to do that go back to the accept control panel and search for the button called Explorer it should be this button on the side with this folder icon click on it and this will open up the file explorer on your machine there are a lot of folders here but as usual you can safely ignore a lot of them these files just help you create a server on your machine the only photo we care about is the one called htdocs htdocs is short for hypertext documents I want you to go into this folder and you should see a couple of files you may have different files than I do because I deleted those and created some new ones I actually use xampp often for web development anyway you can delete every single default file you see in this folder as you don't need them they're usually just files to help you get started with xampp I want you to grab that index file you unzipped earlier and place it inside this folder I'm going to do that now all right so I just placed the file inside this folder as you can see here I'm going to refresh the localhost page again and you should now see the documents appearing like so just like that you have your very own server you don't have to write a single line of server logic as it's taking care for you by except to reiterate d3 is a client-side library see don't actually need a server however we'll be requesting data from external sources which does require a server or else the browser will throw an error anyway now that you have a server you can then edit the files in any editor you like it is now required to use webstorm for this course I'll be using web forms built in server because it's more convenient if you're using X app then you'll need to place all your files inside this htdocs order I do recommend you organize your files inside folders as will be working with quite a few projects let me show you how to access files from different folders it's quite simple I'm going to create a folder named example and then I'm going to drag and drop the index that HTML file inside this folder once you have that set up you can then go back to localhost and change the URL to localhost / example you should still be able to see the message like before all right and that does it for now I'll see you in the next lecture before we write a single line of code I want to give you a general overview of what data visualization is and why it's important this course focuses on the code only but it's important to understand some of the fundamental concepts I'm about to present as it'll help you better approach your projects so the question is what is data visualization data visualization is the ability to convey a story or an idea as efficiently as possible as the old saying goes a picture is worth a thousand words it's so that the end the user can better understand a situation or story as a result the data visualization should allow the user to make an informative decision or just learn something new data visualizations can also help us explore patterns looking at a spreadsheet or table of data makes it harder for users to visualize patterns without a proper visualization we could end up missing small disruptions in our data and which is even worse so data visualization is an absolute important part of data science if we were to break down most visualizations we would find that most visualizations are made up of shapes colors and size with just these three building blocks we give the user insight about the data they're viewing it's important to note just how much of an impact a visualization can make hopefully you're given a job to present data in an unbiased and non-leading way it's our job to present the data that's easy to understand and not necessarily sway them one way or another I'm starting to jump into a gray area so I'll leave it at that let's move forward so now that we understand what data visualization is and its benefits let's explore what makes it good data visualization here are five tips for making a great visualization first before you write a single line of code it's a point to understand the context of the data visualization you need to ask yourself the following questions who is the audience what did they need to know what did they need to deal with the data it's important you answer these questions before you start writing anything tip number two would be choosing an appropriate visualization you can only choose the visual after you know who your audience is in the resource section of this lecture I provide a link to a blog post about how someone chose a visual for a certain project be sure you read this so you can better understand the process the site visit is is also a great resource for learning data visualizations and I highly recommend you check it out alright let's move forward being next creating a good visualization is removing clutter or unnecessary information when you received ela there is a probability that the data may have information that's not important for visual display this tends to be common in maps you'll have data that contains the coordinates and names of the area you're drawing along with the data you may have types which aren't supposed to be displayed visually now later in this course you'll understand what types are but for now just understand there are some situations where certain data shouldn't be displayed anyway sometimes you have data that's more important than others so you may prioritize it visually and push other data to the side for the user to look at later this leads me to tip number four and draw attention using shapes size and color if you have something that the user should primarily focus on then don't be afraid to make it larger or make that piece of data stand out it's a very strict fourth tip but a lot of data visual designers really don't bother making dividuals more interesting tip number five is to make sure your data tells a story this is something you'll learn through experience and by studying other data visualizations some of the greatest data visuals out there tell a story in the resource section of this lecture I provided a link to a blog post by Google about the importance of telling a story with data at the very beginning there is a quote here which really resonates with me and summarizes why telling story is important most organizations recognize that being a successful data-driven company requires skilled developers and analysts fewer grasp how to use data to tell a meaningful story that resonates both intellectually and emotionally with an audience marketers are responsible for the story as such they're often the bridge between the data and those who need to learn something from it or make decisions based on its analysis as marketers we can tailor the story to the audience and effectively use data visualization to complement our narrative we know that data is powerful but with a good story it's unforgettable read the rest of this article and watch the video to help you better understand in this tip so we've gone over what they the visualization is let's talk about how D 3 plays into all of this D 3 stands for data-driven documents I would say that's a great description for what d3 does d3 helps you close the gap between the data in the visualization in order to create visualizations on the web you need to be able to calculate a lot of things such as size position color text etc this gets even harder when you bring interactivity to your graphs d3 assists you for providing a set of functions for displaying your data on to the document in the documents being the web page the user views on the browser d3 is very specific on how you should go about creating data visualizations it's in the name you basically have two main parts you have the data itself and then you have the document the data is what drives the visualization it should never be the other way around your visualization should represent the data no matter what it looks like or how its structured your visualization should not determine if the data itself changes for example if you have extra space a room on your graph then that shouldn't mean the visualization should add something to the data itself instead the visual needs to be adjusted not the data throughout this course we'll tackle projects in a certain process we start off with retrieving the data and preparing some settings then we'll prepare any functions we'll need and then we begin drawing everything onto the page using the data and the functions lastly we'll add any interactivity if there should be any you'll get a lot of practice with this process so don't worry if you don't fully understand it before I finish this lecture let's explore some examples of good in bad visualizations let's start with some bad ones this first example is pretty straightforward it's a pie chart that shows you how much gold is distributed among countries as you can tell it doesn't provide much information visually which just makes it terrible in this next example has too much visual information it really doesn't highlight what's important and there's simply too much clutter this is an example of too much clutter and possibly a wrong choice for a visual since there's so much data the author should have picked a graph that handles this much data this next example is an example of data that is accurately represented but it's extremely misleading and this graph is comparing two CPUs by measuring the FPS in a particular game the difference is only one frame but this makes it seem like one CPU is vastly superior to the other if you're not tech savvy with this stuff then I'll fill you in one frame isn't actually that big of a difference in some scenarios for certain data if one number difference can be huge however in this example a single frame isn't a big deal if the frame difference was intense then it would make sense but this is simply misleading let's explore some examples of nicely designed graphs in the research section of this lecture I provide a link to a blog post about the repetitiveness in pop lyrics this post is just filled with great visualizations and examples the color choices gray and everything fixed nicely they even took the time to make the post interact with the graphs itself let's look at one more in the resource section of this lecture I provided a link to a post about the US workforce and what it looks like now another great post where as you scroll down the visual changes even if you're not interested in the data itself the visual is something worth looking at it can show you what you can do with data visualizations and how you can tell incredible stories alright that's it for now that does it for this section in the next few sections we'll begin coding and learning about the wonderful world of d3 I hope to see you there in this lecture we're going to learn about something called SVG SVG is short for scalable vector graphics d3 heavily relies on SVG to create the grass and charts it generates SVG has been around for a long time and they're quite powerful SVG is a text-based image format whenever we think of images we tend to think of a group of pixels on a screen all combined together to make up something we can visually recognize you can use programs like Photoshop or Microsoft Paint to create images the phones on cameras can take pictures in which we can upload onto the web as an image some of the most common formats for images is jpg PNG and gifts another format is SVG however as Fiji's aren't generated like traditional images rather than it being something that a program or device can generate it's generated with code code that you can read or write there are some programs out there that can generate SVG images but we'll get to that soon enough I want to take a step back for a moment and take a look at this phrase scalable vector graphics this may seem like an odd name but it's not once you understand what each word means let's start with vector first a vector is an image generated through math equations and commands let's take a look at a vector in a regular image right now I have a program called illustrator open you do not need to have Illustrator installed as this is just an example as you can see I have these two circles the one on the left is a vector and the one on the right is a regular image from this distance they both look fairly normal but let's see what happens when I began to zoom in on both of these images as i zoom in you'll notice that the vector on the left still looks nice and crisp but the image on the right is starting to look pixelated eventually we'll come to a point with the vector image just looks so much better than the regular image it doesn't matter how far we zoom in or out the vector will always look consistent and clean the regular image will continue to look distorted and pixelated this is because the vector is created using math to always look good let's take a look at another example I'm going to zoom back out so we can see both images if you've ever tried to resize an image you should know that the result is never really that great unless the image is high quality and big even then the results won't be that great I'm going to resize the image on the right I'm going to change its height and make it look like a squeezed circle as you can see the width of the edge of the circle loses its consistency the sides on the left and right are nice and thick but the top and bottom are thin I'm going to do the same 2d vector image as I scale it down it the vector image will keep it to width no matter what size a scalar - this is what's called a scalable vector graphics it's an image that's created using mathematics and commands it can be scaled to be smaller or larger and it will never become pixelated the advantage to using SVG images is clear now you may be wondering why don't all images just be SVG images well that's a really good question and the answer is quite simple SVG images require a lot of resources if you want to have an that is extremely detailed then you will require a lot of power to generate this image even trying to move it can be difficult SVG images are perfect for basic shapes and graphics it's primarily used for creating animations or web graphics it's also great for comics and basically anything that isn't super detailed illustrator allows you to export any image you create as PNG JPEG GIF and even an SVG image I'll show you how to do that soon but let's take a look at what's inside an SVG image I told you earlier that SVG images can be created with code and the next lecture we'll see how to do just that before you move on to the next lecture I want to make one important note since we'll be using d3 DT will take care of doing the heavy lifting SVG images can become really complex really fast especially when your data is complex and big the purpose of the d3 library is to make things easier for you you don't have to memorize every single elements and attribute there is for SVG images it's important that you understand what's going on and why certain things behave the way they do anyway I'll see you in the next lecture creating SVG images is fairly easy right now I have a basic HTML document you can just use the document I provided earlier and clear the JavaScript code we won't be needing the JavaScript portion at the moment by default most browsers support SVG images fairly well so you shouldn't have any problems when using SVG creating an SVG is as simple as creating the element SVG this is the minimum requirement for creating an SVG image the SVG element is a container for all your graphics the browser will look at this and know that you want to create an inline SVG image and this element can have a lot of attributes but let's keep things simple I'm going to apply two attributes called width and height as you may have expected this will give the element more space on the page it's always good practice to give your SVG images a set width and height I'm going to set both for these to 500 I'm now going to go to view open and browser which will boot up the server and open up a new tab after the page has been loaded you'll see that nothing really appears and that's to be expected since we haven't really created anything besides setting the width and height of an image I'm going to right click and select inspect elements this will open up the developer tools and set the tab to elements we previously discussed on what the console and source types are for but now we'll be working with the elements tab the elements tab allows you to view your HTML documents in real time this is different from viewing the page source if you were to right-click on the page again and select view page source you'll have a new to have opened up with the documents being displayed as raw text this is the document as it's being served by the server however once it's loaded by the browser then no longer updates the elements tab inside the developer tools allows you to view the documents and any changes made to it for example you would be able to see when an element disappears or when a new one is added one of the great things about this tab is that you can actually edit and modify elements as well if I were to hover my mouse over these elements you'll see on the left that certain areas are highlighted in blue this is telling us how space is being taken up in where the element is being placed if you look at the documents closer you'll see the SVG element here after hovering my mouse over this element and you can see it's spa on the page from this tooltip here we can see that the size for this element is 500 pixels by 500 pixels this is exactly how we defined it earlier which is great something I want to highlight is that SVG elements can behave like a regular HTML element you can apply classes IDs and even bind JavaScript events to this elements this is one of the reasons why D 3 uses SVG and not only can they adapt to any size but they can be easily modified to suit our needs this will allow us to make our charts and graphs more interactive let me prove this to you will keep things simple I'm gonna go back to my editor and I'm going to remove these width and height attributes we're going to apply these changes through CSS I'm going to apply the ID attribute and set it to CTR which is short for container then inside the head tags I'm going to create some style tags usually I would load an external starchy but this is a very basic example so I'm not too concerned on organization right now I'm going to select the SVG element which would be hashtag CTR we can now apply the normal width and height properties they both should have 500 pixels as the value all right I'm going to refresh the page one more time and nothing should really change on the page but if we look at the elements tab you should be able to select your SVG elements to the far right you'll actually see all these Styles applied to an element as you can see the width and height were both set to 500 pixels throughout this course we'll be using a combination of CSS HTML and JavaScript to create our graphs some people think they can just use one technology to achieve the results but that sometimes makes things harder and they have to be get into the habit of using a combination of technologies to achieve your results it really will make things easier for you I also want to mention that sometimes you won't be able to use CSS to make changes to elements there are some elements related to SVG that can't be modified through CSS that's perfectly fine in these cases you can just use the HTML attributes in the next lecture we'll start actually creating some vectors I'll see you there in this section we're going to start with the basics of d3 we're not going to create anything fantastic before we can create complex graphs and charts we need to understand the core d3 API so let's get some things set up and right now I'm inside a new directory I want you to create a new folder and point your editor to that directory if you're using xampp make sure you create your directory inside the htdocs folder you don't have to name it anything special just keep it simple I'll be using webstorm server for this in the research section of this lecture I provided a zip file that contains some starter files drag and drop the contents of that zip file into your directory what you end up having is two files the index.html file just contains a basic HTML structure there is one important thing I want to highlight about this file and that's setting the character set to utf-8 we will be dealing with a lot of data and functionality so this will ensure that the browser will understand decode at d3 generates then there's the app that jeaious file which is just an empty javascript file I call my foul app that jeaious but you can name this whatever you want once again just keep it simple we'll be modifying these two files soon enough once you have the basic files and folders set up let's actually add d3 in the resource section of this lecture I provide a link to the github repository for d3 if you're not familiar with github and that's fine and github just provides a place for developers to host and share their code with other developers there are a couple ways to download and include d3 into your projects I find the easiest way is to just use the CDN they provide and there are two versions here and they're the exact same thing except for one the standard version includes the file as it has been written the dot min version as you can see here includes the same code as the standard version except all the indentation and whitespace has been completely removed this is useful for when you're releasing your work on to production it allows for faster loading times on your web page the only problem is that the file is hard to read when it comes to developments generally as a rule of thumb you use the standard version when you're in development this allows you to open up the file and easily read the code to better understand what's going on once you're finished writing your script then you just change this to the dominant version production men is short for minified all right some just going to copy and paste this one line of code into my HTML file like so for this course we'll be using version for point 11 if you see a higher version didn't feel free to use it all Cody right will be compatible with future versions as well that's another great thing about d3 it's very easy to upgrade from version to version with minimal breaking changes before we continue on I do want to highlight one thing if you've ever used d3 in earlier versions then you're probably used to including one library usually most libraries you just include one file in your set however recently d3 has split itself up into various files if you were to go back to the github repo and scroll up you find a link to the users profile which is d3 under this profile you'll see all the libraries uploaded by them in this case all d3 related code is placed here when d3 first started it was a basic library to deal with creating SVG elements through JavaScript as it grew peafowl site became alarmingly large the file size was simply too much just for including d3 especially if you only planned on using some of the basic graphs the developer behind d3 decided to break g3 into various components with each feature into its own library this is great because now you only have to include code that you plan on using the file we've included includes everything out of the box this will save us some time from having to include every single bit we need the trade-off is that the page may load slower than normal throughout this course I'll be sure to tell you what libraries were using and where you can find them for now we'll be using everything the last thing I want to do is just include my app that J's file below the inclusion of the DP scripts let's check if everything is working I want you to boot up your server and then view this page for me it's as easy as going to view open and browser you should see an empty page you should check the console tab of the developer tools to make sure you're not getting any errors all right so we have everything we need in the next lecture we'll start coding everything data when you hear that word what do you think it means it's a very broad term that can mean a lot of things what exactly is data and me programming a technology world data is almost everything images audio files text the browser you're using to watch this video is data it's a bit hard to understand it like that but that's what data generally is luckily when it comes to d3 data is broken down to be more specific data to d3 is just text and numbers and generally speaking your data can come from four sources you can hard code it into your JavaScript file which is what we'll be doing in the beginning then there's data that comes from external sources you can place your data in text files also known as txt files there's also JSON which is a JavaScript object in its own file lastly in there spreadsheets or CSV files which is short for comma separated values all three these file types can be used with d3 easily data really can't do anything by itself when it comes to data visualization there are two parts to it and there's the data itself which can be text or number based for example the amount of dog owners in certain cities or how many students hold a certain grade all of this will be considered your data then there's the second part which is the visual part for this course and that would be HTML and CSS the average user can't understand the raw data or understand HTML and CSS that's where the challenge comes in combining these two parts together into something the user can understand hence the phrase data visualization d3 is the library that bridges that gap and it makes it easier for you to combine the data and the visual part together right now let's focus on learning how to make elements appear on the page later we'll learn how to add data into the mix right now I'm inside my editor and I have both my index.html and app that J's files opened up to start things off I'm going to add my code inside the JavaScript file when you load it d3 3d script tags you're provided an object called d3 this object will contain all the properties and methods related to d3 usually the first thing you'll want to do is select an element doing that is very simple the d3 object has a method called select he simply passin a CSS selector of the element you like to grab for example if you wanted to select an element with a certain ID then you just pass in the hash tag followed by the ID name so if I had a div tag with the idea of foo then I would pass in hash tag foo for classes you would use a dot instead of a hash tag lastly if you just wanted to select a plain HTML element then you will just pass in the elements name so if I wanted to select a paragraph then I would pass in P basically anything you can select with CSS can be inputted here this is one method of selecting an element another method is by using the select all method this works the exact same way as deselect method except for one thing the Select method will grab the first element it finds for example if I pass in the paragraph tag then this will select the first paragraph element it finds even if we had multiple paragraph elements on the page this will still only grab the first one if you want it to grab all the paragraph tags on the page then you should use the select all method which does this so we have two methods here for selecting an element but I'm going to just stick with select method for now I'm also going to change this to select the body elements we don't have a paragraph tag but we do have the body elements which will work for now I'm going to create a variable named L which is short for element and assign it to this value right below this I'm going to console dot log the element I want to see what exactly is going on internally I'm going to boot up my server by going to view open in browser nothing is going on in the browser which is to be expected so let's check out the console inside the console we have an object being logged which is called selection a selection is a JavaScript object that represents an HTML elements on the browser this is very important to understand as selections are the most common objects you'll be working with essentially when you're working with SVG elements and they are referenced as a selection object in the resource section of the structure I provide a link to the d3 selection repository this basically documents and contains all the code for the d3 selection library as I stated earlier d3 has separated itself into various libraries for optimal performance the developer behind d3 has gathered a lot of data and has determined that the selection library is commonly used so he decided that it should be part of the core by default you don't have to include this as it's already part of the core however if for whatever reason you just want to use the selection library by itself then you can just download it here so basically the selection library is a way to select and change HTML elements it's a very basic library feel free to read up on this page to learn more about it we will discuss many of its features throughout the course you will definitely get a lot of practice with it anyway let's go back to the page and view the console tab again inside this you'll see that the selection object contains two properties called groups and parents we won't be diving too much into these two as it's not required to know this is really for d3 and their browser to understand and use and generally the parents property contains the elements that the element were currently selecting is contained in the group's property contains an array of the elements we selected let's look inside the group's property since we're using the Select method you would usually only see one element in the array which is fine by us eventually going deep enough you find the elements with all the data applied to it there's a lot going on here all we did was write one line of code and all of this was created for us for the most part we don't have to worry about a lot of this as its handle for us by d3 what I do want to highlight about this data is the element itself right here the body tag is represented here for us this is not a string this is the actual element itself if I were to hover my mouse over this element then you'll see my browser at the top highlighted for us it'll be represented by this orange red rectangle of the page itself I can even click on this and I'll be taken to the elements tab of the developer tools the developer tools will automatically select the elements or selecting in JavaScript this is one way to verify what elements you're currently using so basically d3 has given us a way to reference the actual element on the page if you've ever used jQuery then this concept should be familiar to you let's take a look at what a list of elements looks like back inside my file I'm going to change the select method to select all and change body to P we don't have any paragraph tags inside the h2 my document so this should return nothing once you have this changed go to the HTML file and add a couple paragraph tags I'm going to add three with that all setup and let's refresh the page and check out the console as usual we have the selection object being displayed and we have the group's array populated with all our elements I added three paragraph tags so I'll see three paragraphs being selected one difference you may notice is at d3 Morpher to this as a node list you'll hear the word nodal are in tutorials and even in your code basically a node is the technical term for anything and everything in your document that seems strange to hear but that's what it is your elements are nodes the attributes inside them are nodes even the text inside your elements are nodes so when you see the word node list it's basically saying a list of HTML elements for the most part you don't have to worry about the technical words here as it's just for d3 in the browser so don't worry about it if you don't fully understand alright I'm going to remove these paragraph tags and change my code back to its original state I don't plan on using these at all I want to keep everything simple for now the last thing I want to show you is how to add elements usually when you select some elements you want to add on to it adding another element is very simple right after selecting the element you can use the append method this method is also a part of the d3 selection library even though the select method returns the selection we still have access to the d3 library itself this is taken care of for you it's the magic behind a d3 library this method accepts the name of the element you'd like to create I'm going to keep it simple and pass any paragraph tag let's refresh the page and see what we get if you were to view the elements tab then you should see the P tags inside the body tag so basically the append is doing two things it's creating the element and then it's adding on to the current selection in this case it would be the body tag it's important to note that the elements will be added inside the selection at the very end this is why the paragraph tag appears right below these script tags let's read the object now you'll notice that the selection changes to the P tag rather than the body tag this is to be expected d3 will shift its focus to the element you just added when you use the append method behind the scenes d3 will call the Select method for you in passing the elements you just created by doing this you are no longer manipulating or using the body elements anymore it's very important you understand this back inside my code you'll see that I'm chaining all this together the idea of calling one method after the other is called chaining methods this is something that d3 heavily adopts if you were to view any examples from d3 then you'll see there's a lot of chaining this is something I want you to get used to we'll be using a lot of training methods in most cases a lot of methods return the selection you have if you don't understand or don't know what a method returns then it's always a good idea to log the data or just check out the documentation d3 is really well documented and will usually tell you what you can expect after calling a certain method of course you can break this chaining method by using variables let's say I want to have your variable for both the body tag and paragraph tag well that's simple to do right after selecting the body tag I'm going to add a semicolon then I'm going to create a new variable named P and set its value to L that append like so I'm writing a like this is the same way we had before and the only difference is that now we have two selections being stored if you wanted to continue adding up to the body element then you can just reference it using the L element like we do in the second line if you wanted to add more stuff to the paragraph element then you can just reference it using the P variable as the course progresses you'll see me changing methods and sometimes breaking that chain you can use either style but I usually like to mix them both together for readability and reusability it's all preference I'm going to undo these changes and just go back to what we had before there's no need to break down our code like this right now anyway that does it for now and there's actually a whole lot more things you can do with selections but we'll explore that as the course progresses I'll see you in the next lecture in the previous lecture we took a look at selections and how to create elements at this point you should have a basic understanding of the selection library and I will take a look at how to manipulate those selections right now I'm looking at the d3 selection page if you scroll down a bit further you'll come across the API reference section we've already gone over selecting elements so now we'll be taking a look at modifying elements here is what d3 has to say about these methods after selecting elements use the selections transformation methods to affect document content so basically be set of functions will allow you to add and remove attributes you can also change the content and sight elements that you have selected it is a point that you have a selection before you apply these methods I'll talk more about that later in this lecture let's get started the first thing I want to do is add some attributes to do that we need to call the attributes method I'm chaining this right after appending the paragraph tag in this case the attribute will be applied to be para tag since that is the current selection if I wanted this to be applied to the body target then I need to call this method right after selecting the body tag for now I want to apply this attribute to the paragraph tag this method has two parameters which is the name of the attribute you'd like to add and the value one of the most common attributes you find yourself adding is the class attribute so let's pass that in as the first value the second parameter for this method is optional but usually you'll set it anyway and this will be the value for this class I'm going to apply the Foo class we haven't defined this class but that's okay for now and this is just an example just for fun let's use another function right after this I'm going to change another method called text as the name describes and this will add text inside the current selection I'm going to set this to hello world I promise I'll break down a lot of this but let's check to see if it's working first and boot up your server and navigate to this page we should see the paragraph tag being displayed and would be text inside if you were to view this insightly developer tools then you should see the class field being applied to this element this is exactly what we wanted so now that we have that working let me break down what's going on back inside the editor I want to format my code a bit when it comes to d3 you'll be doing a lot of chaining when you're chaining two or three methods it doesn't really look that bad but we're going beyond that here having your code all in one line just makes it really hard to read so I'm just going to indent everything this right here is preference in what works for you in a lot of examples you'll usually see code formatted like this so it's good practice for you to get into the habit of a tool with that formatted let's explore these two methods I just introduced d3 refers to these methods as transformation methods while they are provided inside the selection library they do have a couple of differences from the methods we used in the previous lecture as the name suggests these will change how an element appears or works internally with that being said they will only work if you apply them to a selection made previously the order of methods matter a lot here if I were to directly call this method at the very start of a chain then this will simply not work another thing you should know is that transformation methods will return the selection it's being applied to these methods will not create a new elements nor will they select a brand new element this is why I can call the text method right afterwards this attribute method will add the class foo to the paragraph tag and then it will return the paragraph selection to be used by the next method in this example and this would be the text method and of course the text method will return the same paragraph selection in my code you can see that I'm still logging the element into the console let's go back to the browser and see what selection is returned as expected we should see the panic attack being selected it you'll see that the class foo is being appended to the name this is great because we have a real timer presentation of the elements in JavaScript if you're adding an attributes that isn't a class ID then you most likely won't see it like this there are two ways to check if an attribute is added you can go to the elements tab and check the elements yourself here I see the class is definitely being applied alternatively you can check the console and look into each object deeply inside this object I can see we have a property named attributes this is where all the HTML attributes are stored eventually after digging through a little bit I'll find me class attributes and its Valley foo I know I've said it a few times but I'll say it again it's not important that you understand what's inside these objects a lot of this is for d3 to use usually I don't find myself looking into these objects since everything is generated in HTML form when I do look into these objects it's because I'm desperate and I don't understand what's going on in these cases I try to understand the JavaScript object deeply provides so I can be bug my code properly the attribute property is the one I find myself checking me most all right now that we understand that let's go back to our script so one thing I want to mention is that the attributes method will override in attributes even if it exists for example right now I'm adding the class foo but let's say later in my program I wanted to add another class well let's see what happens when I call the attribute method Lippe values of class and bar and this should add the class bar to the elements after making these changes let's refresh the page and inspect the element as you can see here the class foo is completely gone this is because the attribute method remove the original value and replaced it with the new value and there are two solutions here we could update the attribute method to contain both classes but this isn't practical this is because data can be dynamic if we needed to apply classes after a while and trying to rewrite the attributes can become hard to manage luckily DG provides an alternative method for this I'm going to come to up both these method calls and then I'm going to call a method called class this is a special method meant specifically for adding and removing classes from an element and you simply pass in the class name and then whether it should be added or removed the class I want to add is Phil to specify if it'll be added or removed and you just hasn't true or false respectively I want this to be added saw set this to true if this class already exists then nothing happens I'm going to call this method again except this time I'm going to pass in bar and also set this to true the great thing about this method is that it won't completely overwrite the attributes let's refresh the page and see what we get as expected we'll now see both classes being applied there's one last thing I want to show you and that is adding inline CSS it's very simple and you may have an idea of how it would look like at the very end of this chain I'm going to call the style method and this works at the name of the CSS property and its value I'll keep it simple and set the color property to blue refresh the page after making these changes the text has now turned blue so that's how you would manipulate selections there's actually more things you can do but we'll learn more about those as the course progresses one of the most important things you should understand is whether a not a certain method will return a new selection or return the one it's being applied to it's always a good idea to check out the documentation to confirm just in case you forget you
Info
Channel: Luis R
Views: 18,376
Rating: 4.6909494 out of 5
Keywords: d3js, tutorial, learn, data visualization, svg, responsive, scales
Id: Xzi5IqlHmhw
Channel Id: undefined
Length: 58min 54sec (3534 seconds)
Published: Fri Nov 17 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.