<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ D3.js - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ D3.js - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 25 May 2026 05:06:14 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/d3js/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Learn Interactive Data Visualization with Svelte and D3 ]]>
                </title>
                <description>
                    <![CDATA[ Data is everywhere, but raw numbers on a screen rarely tell a compelling story. To uncover insights and communicate them effectively, you need to make that data visible and interactive. We just posted a new course on the freeCodeCamp.org YouTube chan... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-interactive-data-visualization-with-svelte-and-d3/</link>
                <guid isPermaLink="false">6877db3efdf62027f80a0a49</guid>
                
                    <category>
                        <![CDATA[ D3.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Wed, 16 Jul 2025 17:02:54 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1752685386541/baf25f0a-a6ff-406f-b0c7-eddb82ed05f6.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Data is everywhere, but raw numbers on a screen rarely tell a compelling story. To uncover insights and communicate them effectively, you need to make that data visible and interactive.</p>
<p>We just posted a new course on the <a target="_blank" href="http://freeCodeCamp.org">freeCodeCamp.org</a> YouTube channel.</p>
<p>In this course, instructor Gregory Kirchoff will guide you through building beautiful, interactive data visualizations from scratch using the power of Svelte and the flexibility of D3.</p>
<p>Here are some of the key concepts covered:</p>
<ul>
<li><p>How to build a simple, bare-bones scatter plot to understand the core concepts.</p>
</li>
<li><p>Setting up and managing an SVG canvas for your visualizations.</p>
</li>
<li><p>Handling data scales to map your data values to pixel coordinates on the screen.</p>
</li>
<li><p>Adding interactivity to allow users to dynamically update the chart.</p>
</li>
<li><p>Bringing your charts to life with smooth animations and transitions.</p>
</li>
<li><p>Making your visualizations responsive so they look great on any device.</p>
</li>
<li><p>Fetching and parsing real-world data from external sources.</p>
</li>
</ul>
<p>To keep things engaging, you’ll work with fun and unique datasets, starting with the results from a pig racing league and later using the Pokémon API to compare stats like weight, height, and speed.</p>
<p><a target="_blank" href="https://youtu.be/XSJD5ay1D_8">Watch the full course on the freeCodeCamp.org YouTube channel now</a> (1.5-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/XSJD5ay1D_8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn how to build security into AI ]]>
                </title>
                <description>
                    <![CDATA[ Artificial Intelligence is changing how we build software, but it also introduces brand new security risks. If you're a developer or security professional stepping into the world of AI, how do you make sure your applications are safe? We've just publ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-how-to-build-security-into-ai/</link>
                <guid isPermaLink="false">6877d9b440b18dbe521d8687</guid>
                
                    <category>
                        <![CDATA[ D3.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Wed, 16 Jul 2025 16:56:20 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1752685029144/e988baa2-4c5f-4670-bac8-d40281f7b324.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Artificial Intelligence is changing how we build software, but it also introduces brand new security risks. If you're a developer or security professional stepping into the world of AI, how do you make sure your applications are safe?</p>
<p>We've just published a new course on the freeCodeCamp YouTube channel that will teach you how to build security into AI. The course was created by security expert Robert Herbig.</p>
<p>Here’s a quick look at what you'll learn:</p>
<ul>
<li><p><strong>AI vs. Traditional App Security:</strong> Understand why securing an AI model isn't the same as securing a standard web app.</p>
</li>
<li><p><strong>Threat Modeling for AI:</strong> Learn how to identify potential weaknesses in your AI systems, from poisoned training data to supply chain attacks.</p>
</li>
<li><p><strong>Input &amp; Output Risks:</strong> Dive into specific attack vectors like prompt injection and adversarial examples, and learn how to prevent sensitive data leaks.</p>
</li>
</ul>
<p>As Robert says, "Security must be a foundational layer in AI development, not an afterthought."</p>
<h2 id="heading-watch-the-full-course-now-on-the-freecodecamp-youtube-channel-1-hour-watchhttpsyoutube0xah5jmflci"><a target="_blank" href="https://youtu.be/0xah5jMflcI">Watch the full course now on the freeCodeCamp YouTube channel (1-hour watch).</a></h2>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/0xah5jMflcI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Visualize Weather Data with D3.js ]]>
                </title>
                <description>
                    <![CDATA[ What plans would you make if you knew it was going to rain tomorrow? This can be a crucial question to ask yourself when it comes to planning your personal and day-to-day business activities. For example, I have a friend who runs an app-based laundry... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/visualize-weather-data-with-d3js/</link>
                <guid isPermaLink="false">66d4616a55db48792eed3faf</guid>
                
                    <category>
                        <![CDATA[ D3.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data visualization ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Spruce Emmanuel ]]>
                </dc:creator>
                <pubDate>Mon, 17 Jan 2022 16:59:10 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/reza-shayestehpour-Nw_D8v79PM4-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>What plans would you make if you knew it was going to rain tomorrow?</p>
<p>This can be a crucial question to ask yourself when it comes to planning your personal and day-to-day business activities.</p>
<p>For example, I have a friend who runs an app-based laundry business in Lagos, Nigeria. He relies heavily on sunshine, and sometimes it rains, or there's just no sunshine. On those days, business is very bad.</p>
<p>But what if he knew it was going to rain the next day or in 6 hours? That would help him plan things well in advance and prevent delays in orders. But where can he get such information?</p>
<p>That's where the Tomorrow.io <a target="_blank" href="https://www.tomorrow.io/weather-api/">weather API</a> comes in. The weather API provides us with accurate and fast weather data in real time, like precipitation probability, amount of rainfall, temperature, wind speed, and more.</p>
<p>Such information is very useful to businesses across various industries like transportation, agriculture, and, in my friend's case, laundry shops.</p>
<p>Also, the weather data from this API can be easily integrated into your project or any program you are working with. The best part – the free version of the API is extremely powerful on its own, so that's what we'll use today.</p>
<p>In this article, we'll use the Tomorrow.io weather API and <a target="_blank" href="https://d3js.org/">D3.js</a> to forecast and visualize the precipitation probability of a particular location on a line chart. A service like this would allow my friend to tell on which days of the week it is likely to rain.</p>
<h2 id="heading-project-requirements">Project Requirements</h2>
<p>What do you need to continue in this tutorial? Basic knowledge of JavaScript and D3.js is required.</p>
<p>I suggest reading a <a target="_blank" href="https://www.freecodecamp.org/news/d3js-tutorial-data-visualization-for-beginners/">beginner's guide to D3.js</a> if you want to refresh your memory before going further.</p>
<h2 id="heading-getting-started">Getting Started</h2>
<p>First, create an HTML file, and add the latest library of <code>d3.js</code> to the HTML file. Also, create an empty <code>svg</code> element, like so:</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Tomorrow.io Rainfall probability<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://d3js.org/d3.v7.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">svg</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h2 id="heading-how-to-set-up-the-margins">How to Set Up the Margins</h2>
<p>At some point, our visualizations will need some space (margins). It is a convention in <code>d3.js</code> to set up the <strong>margin convention</strong>.</p>
<p>For this, you need to define the margins for the four sides, create an <code>index.js</code> file, and add the following:</p>
<p><code>const margin = { left: 120, right: 30, top: 60, bottom: 30 }</code></p>
<p>Now, let's set the width and viewBox of our SVG element. This will help make it responsive.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> width = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"body"</span>).clientWidth,
  height = <span class="hljs-number">500</span>;

<span class="hljs-keyword">const</span> svg = d3.select(<span class="hljs-string">"svg"</span>).attr(<span class="hljs-string">"viewBox"</span>, [<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, width, height]);
</code></pre>
<h2 id="heading-how-to-define-the-scales">How to Define the Scales</h2>
<p>The d3.scale function takes in data as input and returns a visual value in pixels. d3.scale needs to be set with a <strong>domain</strong> and a <strong>range.</strong> The domain sets a LIMIT for the data we are trying to represent visually.</p>
<p>As seen above, we need to set the range of the scales. We'll set the <code>domain</code> once we fetch our data:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> x_scale = d3.scaleTime().range([margin.left, width - margin.right]);
<span class="hljs-keyword">const</span> y_scale = d3.scaleLinear().range([height - margin.bottom - margin.top, margin.top]);
</code></pre>
<h2 id="heading-how-to-add-a-title-and-labels">How to Add a Title and Labels</h2>
<p>Next, we need to add a title and labels to our visualizations. This is useful for explaining our graph to our users.</p>
<p>Edit your <code>script.js</code> and add the following code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// labels</span>
<span class="hljs-keyword">const</span> x_label = <span class="hljs-string">"Time"</span>;
<span class="hljs-keyword">const</span> y_label = <span class="hljs-string">"Rainfall Probability"</span>;
<span class="hljs-keyword">const</span> location_name = <span class="hljs-string">"Lagos Nigeria"</span>;

<span class="hljs-comment">// add title</span>
svg
  .append(<span class="hljs-string">"text"</span>)
  .attr(<span class="hljs-string">"class"</span>, <span class="hljs-string">"svg_title"</span>)
  .attr(<span class="hljs-string">"x"</span>, (width - margin.right + margin.left) / <span class="hljs-number">2</span>)
  .attr(<span class="hljs-string">"y"</span>, margin.top / <span class="hljs-number">2</span>)
  .attr(<span class="hljs-string">"text-anchor"</span>, <span class="hljs-string">"middle"</span>)
  .style(<span class="hljs-string">"font-size"</span>, <span class="hljs-string">"22px"</span>)
  .text(<span class="hljs-string">`<span class="hljs-subst">${y_label}</span> of <span class="hljs-subst">${location_name}</span>`</span>);
<span class="hljs-comment">// add y label</span>
svg
  .append(<span class="hljs-string">"text"</span>)
  .attr(<span class="hljs-string">"text-ancho"</span>, <span class="hljs-string">"middle"</span>)
  .attr(
    <span class="hljs-string">"transform"</span>,
    <span class="hljs-string">`translate(<span class="hljs-subst">${margin.left - <span class="hljs-number">70</span>}</span>, <span class="hljs-subst">${
      (height - margin.top - margin.bottom + <span class="hljs-number">180</span>) / <span class="hljs-number">2</span>
    }</span>) rotate(-90)`</span>
  )
  .style(<span class="hljs-string">"font-size"</span>, <span class="hljs-string">"26px"</span>)
  .text(y_label);
<span class="hljs-comment">// add x label</span>
svg
  .append(<span class="hljs-string">"text"</span>)
  .attr(<span class="hljs-string">"class"</span>, <span class="hljs-string">"svg_title"</span>)
  .attr(<span class="hljs-string">"x"</span>, (width - margin.right + margin.left) / <span class="hljs-number">2</span>)
  .attr(<span class="hljs-string">"y"</span>, height - margin.bottom - margin.top + <span class="hljs-number">60</span>)
  .attr(<span class="hljs-string">"text-anchor"</span>, <span class="hljs-string">"middle"</span>)
  .style(<span class="hljs-string">"font-size"</span>, <span class="hljs-string">"26px"</span>)
  .text(x_label);
</code></pre>
<p>With the above-added title and labels, the preview looks like this:</p>
<p><img src="https://paper-attachments.dropbox.com/s_80A2ED9660649A0944547FE32AE888AF070E268C15D560C813DD3420036CDBBE_1638557381465_tomorrow.io-demo1.png" alt="Added titles and labels to our visualization" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-create-the-line-chart">How to Create the Line Chart</h2>
<p>Here, the first thing we'll need to do is to generate the <a target="_blank" href="https://sharkcoder.com/data-visualization/d3-line-chart">path</a> for our chart. D3.js provides a <code>.line()</code> method that pretty much generates the line path for you. Let's add the line generator:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> start_time = <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(d.startTime);
<span class="hljs-keyword">const</span> temperature = <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> +d.values.precipitationProbability;

<span class="hljs-keyword">const</span> line_generator = d3.line()
  .x(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> x_scale(start_time(d)))
  .y(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> y_scale(temperature(d)))
  .curve(d3.curveBasis);
</code></pre>
<p>Now that we have defined our line generator, let's go ahead and fetch our data.</p>
<h2 id="heading-how-to-fetch-data-from-the-tomorrowiohttptomorrowio-weather-api">How to Fetch Data from the <a target="_blank" href="http://Tomorrow.io">Tomorrow.io</a> Weather API</h2>
<p>D3 provides us with a <code>.json()</code> method to fetch JSON data from an API or a local file.</p>
<p>Before you can fetch data using the <a target="_blank" href="http://Tomorrow.io">Tomorrow.io</a> weather API, you'll need a secret access token. To get this token, all you need to do is create an account with <a target="_blank" href="http://Tomorrow.io">Tomorrow.io</a>. Yes, it's that easy.</p>
<p>Once you have created your account, go ahead and log in. Then, on your <a target="_blank" href="https://app.tomorrow.io/development/keys">dashboard</a>, you should see your API secret token:</p>
<p><img src="https://paper-attachments.dropbox.com/s_80A2ED9660649A0944547FE32AE888AF070E268C15D560C813DD3420036CDBBE_1638566467761_tomorrow.io-demo2.png.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Add the following code to fetch the data:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> lat = <span class="hljs-number">6.465422</span>; <span class="hljs-comment">// latitude of Lagos, Nigeria</span>
<span class="hljs-keyword">const</span> long = <span class="hljs-number">3.406448</span>; <span class="hljs-comment">// Longitude of Lagos, Nigeria</span>

<span class="hljs-keyword">const</span> api_key = <span class="hljs-string">"your-api-key-here"</span>;

<span class="hljs-keyword">const</span> url = <span class="hljs-string">`https://api.tomorrow.io/v4/timelines?location=<span class="hljs-subst">${lat}</span>,<span class="hljs-subst">${long}</span>&amp;fields=snowAccumulation,precipitationProbability,precipitationType&amp;timesteps=1h&amp;units=metric&amp;apikey=<span class="hljs-subst">${api_key}</span>`</span>;

d3.json(url).then(<span class="hljs-function">(<span class="hljs-params">{ data }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> d = data.timelines[<span class="hljs-number">0</span>].intervals;
  <span class="hljs-built_in">console</span>.log(d)
});
</code></pre>
<p>Here is an example of the JSON data returned from that fetch:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"timelines"</span>: [
      {
        <span class="hljs-attr">"timestep"</span>: <span class="hljs-string">"1h"</span>,
        <span class="hljs-attr">"startTime"</span>: <span class="hljs-string">"2021-12-03T13:00:00Z"</span>,
        <span class="hljs-attr">"endTime"</span>: <span class="hljs-string">"2021-12-08T01:00:00Z"</span>,
        <span class="hljs-attr">"intervals"</span>: [
          {
            <span class="hljs-attr">"startTime"</span>: <span class="hljs-string">"2021-12-03T13:00:00Z"</span>,
            <span class="hljs-attr">"values"</span>: {
              <span class="hljs-attr">"snowAccumulation"</span>: <span class="hljs-number">0</span>,
              <span class="hljs-attr">"precipitationProbability"</span>: <span class="hljs-number">0</span>,
              <span class="hljs-attr">"precipitationType"</span>: <span class="hljs-number">0</span>
            }
          },
          <span class="hljs-comment">// 108 more data</span>
        ]
      }
    ]
  }
}
</code></pre>
<p>Now that we've fetched our data, let's generate our line chart:</p>
<pre><code class="lang-js">d3.json(url).then(<span class="hljs-function">(<span class="hljs-params">{ data }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> d = data.timelines[<span class="hljs-number">0</span>].intervals;

<span class="hljs-comment">// set the domain </span>
  x_scale.domain(d3.extent(d, start_time)).nice(ticks);
  y_scale.domain(d3.extent(d, temperature)).nice(ticks);
  <span class="hljs-comment">// add the line path</span>
  svg
    .append(<span class="hljs-string">"path"</span>)
    .attr(<span class="hljs-string">"fill"</span>, <span class="hljs-string">"none"</span>)
    .attr(<span class="hljs-string">"stroke"</span>, <span class="hljs-string">"steelblue"</span>)
    .attr(<span class="hljs-string">"stroke-width"</span>, <span class="hljs-number">4</span>)
    .attr(<span class="hljs-string">"d"</span>, line_generator(d)); <span class="hljs-comment">// generate the path</span>
});
</code></pre>
<p>The above code gives us a basic chart:</p>
<p><img src="https://paper-attachments.dropbox.com/s_80A2ED9660649A0944547FE32AE888AF070E268C15D560C813DD3420036CDBBE_1638560607910_tomorrow.io-demo3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-add-the-axes">How to Add the Axes</h2>
<p>Even with the above line chart, you will have a hard time knowing exactly which day or hour has the highest possibility of rainfall.</p>
<p>We can resolve this by adding the time and rainfall probability (in %) axes.</p>
<p>First, define the axes just below your scales:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ticks = <span class="hljs-number">10</span>;
<span class="hljs-keyword">const</span> x_axis = d3.axisBottom()
  .scale(x_scale)
  .tickPadding(<span class="hljs-number">10</span>)
  .ticks(ticks)
  .tickSize(-height + margin.top * <span class="hljs-number">2</span> + margin.bottom);
<span class="hljs-keyword">const</span> y_axis = d3.axisLeft()
  .scale(y_scale)
  .tickPadding(<span class="hljs-number">5</span>)
  .ticks(ticks, <span class="hljs-string">".1"</span>)
  .tickSize(-width + margin.left + margin.right);

<span class="hljs-comment">// format our ticks to get accurate %</span>
y_axis.tickFormat(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Number</span>.isInteger(d)) {
    d = decimalFormatter(d);
  }
  <span class="hljs-keyword">return</span> d + <span class="hljs-string">"%"</span>;
});
</code></pre>
<p>Finally, let's add our axis on the SVG element:</p>
<pre><code class="lang-js"><span class="hljs-comment">// append x axis</span>
  svg
    .append(<span class="hljs-string">"g"</span>)
    .attr(<span class="hljs-string">"transform"</span>, <span class="hljs-string">`translate(0,<span class="hljs-subst">${height - margin.bottom - margin.top}</span>)`</span>)
    .call(x_axis);

  <span class="hljs-comment">// add y axis</span>
  svg
    .append(<span class="hljs-string">"g"</span>)
    .attr(<span class="hljs-string">"transform"</span>, <span class="hljs-string">`translate(<span class="hljs-subst">${margin.left}</span>,0)`</span>)
    .call(y_axis);
</code></pre>
<p>With the axis added, our line chart now looks like this:</p>
<p><img src="https://paper-attachments.dropbox.com/s_80A2ED9660649A0944547FE32AE888AF070E268C15D560C813DD3420036CDBBE_1638561615864_tomorrow.io-demo4.png" alt="Tomorrow.io precipitation probality of lagos, Nigeria. December 03, 2021" width="600" height="400" loading="lazy"></p>
<p>That's much better! You can now tell which day and hour has the highest probability of rainfall.</p>
<p>The full code and demo for this example is hosted on Codepen:</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/Spruce_khalifa/embed/vYeNKRg" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>With the power of D3.js combined with the <a target="_blank" href="http://Tomorrow.io">Tomorrow.io</a> weather API, we can create visualizations that help users solve weather-related issues affecting their businesses.</p>
<p>I hope you found this tutorial helpful.</p>
<p>Happy Coding!</p>
<p>Cover photo by <a target="_blank" href="https://unsplash.com/@r_shayesrehpour">Reza Shayestehpour</a> on Unsplash</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ D3.js Tutorial – Data Visualization for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ In this article, I'm going to walk you through how to use D3.js in a step by step and beginner-friendly way. We'll talk about what D3.js is, how it works, and we'll create some basic visualizations to add transitions, interactions, and zooming. Table... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/d3js-tutorial-data-visualization-for-beginners/</link>
                <guid isPermaLink="false">66d46150706b9fb1c166b9bd</guid>
                
                    <category>
                        <![CDATA[ D3 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ D3.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data analysis ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data visualization ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Spruce Emmanuel ]]>
                </dc:creator>
                <pubDate>Wed, 24 Nov 2021 15:03:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/11/Group-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, I'm going to walk you through how to use D3.js in a step by step and beginner-friendly way.</p>
<p>We'll talk about what D3.js is, how it works, and we'll create some basic visualizations to add transitions, interactions, and zooming.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-getting-started-with-d3js">Getting Started</a> What is D3.js? How to Set Up a D3.js Environment</p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-select-elements-in-d3">Selections</a> How to Select Elements in D3 How to Modify Elements in D3</p>
</li>
<li><p><a class="post-section-overview" href="#heading-d3-is-data-driven">D3 is Data Driven</a> Data Join in D3 Data Loading in D3</p>
</li>
<li><p><a class="post-section-overview" href="#heading-scales-in-d3">Scales in D3</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-bar-chart-with-d3js">Create a bar chart with d3.js</a> Axis Component in D3 D3 Margin Convention How to Style it With CSS in D3</p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-world-map-with-d3jsone-of-the-things-i-personally-love-about-d3-is-its-ability-to-handle-geographic-data-unlike-our-former-examples-which-used-json-data-format-maps-now-well-use-a-special-form-of-json-data-called-geojsonyou-can-find-the-geojson-data-we-are-going-to-use-herelike-in-our-other-examples-lets-first-select-our-svg-element-in-the-document-and-also-set-up-the-margin-conventionconst-margin-top-5-right-5-bottom-5-left-5-width-documentqueryselectorbodyclientwidth-height-500-const-svg-d3selectd3demoattrviewbox-0-0-width-height-html-next-to-generate-our-map-well-need-a-projection-to-render-spherical-coordinates-in-our-data-file-and-a-path-generator-to-convert-the-projected-coordinates-to-a-svg-path-which-is-then-rendered-on-the-screenlet-projection-d3geoequirectangularcenter0-0-d3-provides-a-lot-of-projections-i-only-used-this-one-because-i-like-it-now-that-we-have-chosen-our-projection-lets-convert-it-to-an-svg-path-d3-handles-the-conversion-for-us-when-we-use-the-d3geopath-method-this-method-takes-in-a-projection-the-one-we-defined-aboveconst-pathgenerator-d3geopathprojectionprojection-we-dont-want-to-draw-the-map-directly-on-the-svg-because-we-are-going-to-be-adding-animations-and-zooming-later-on-so-we-append-a-g-element-to-the-selected-svglet-g-svgappendg-then-well-load-our-data-for-the-mapd3jsonhttpsrawgithubusercontentcomiamspruceintro-d3maindatacountries-110mgeojson-thendata-gt-consolelogdata-if-this-doesnt-make-sense-i-suggest-you-re-read-the-data-loading-sectionlastly-lets-use-our-pathgenerator-to-generate-our-paths-gselectallpath-datadatafeatures-joinpath-attrd-pathgenerator-above-we-used-d3-data-join-to-append-a-path-for-each-country-and-then-set-the-d-attribute-to-our-pathgeneratorattrd-pathgenerator-and-in-case-that-isnt-clear-its-the-equivalent-of-writing-thisattrd-d-gt-pathgeneratord-you-can-find-the-final-code-and-live-preview-on-codepen">Create a World Map with d3.js</a> How to Use Multiple Datasets in D3.js Map with city names Event Handling with D3.js Map with Panning and Zooming Programmatic zooming Adding ToolTips</p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-who-is-this-article-for">Who is this article for?</h2>
<p>This article is aimed at developers who already have a basic knowledge of HTML, CSS, SVG and JavaScript who want to learn how to visualize data with D3.js.</p>
<p>This article is suitable for both complete beginners and those who already have some experience working with D3.js.</p>
<p>By the end of this article, you should understand how D3.js works and how to create visualizations with your data.</p>
<h2 id="heading-getting-started-with-d3js">Getting Started with D3.js</h2>
<p>D3.js is a JavaScript library for creating visualizations like charts, maps, and more on the web.</p>
<blockquote>
<p><strong>D3.js</strong> (also known as <strong>D3</strong>, short for <strong>Data-Driven Documents</strong>) is a JavaScript library for producing dynamic, interactive <a target="_blank" href="https://en.wikipedia.org/wiki/Data_visualization">data visualizations</a> in web browsers. It makes use of Scalable Vector Graphics (SVG), HTML5, and Cascading Style Sheets (CSS) standards. – Wikipedia</p>
</blockquote>
<p>Unlike many other data visualization libraries that provide ready made charts, D3 gives you lots of creative freedom as you have total control over the visualizations you create. D3 also uses web technologies like HTML, CSS, SVG and JavaScript.</p>
<p>In addition to the fact that D3 uses these familiar technologies, it has several other benefits:</p>
<ul>
<li><p>D3 is extremely fast,</p>
</li>
<li><p>It encourages code reusability</p>
</li>
<li><p>It supports large datasets and provides an easy way of loading and transforming data</p>
</li>
<li><p>It's good for creating visualizations with rich interactions</p>
</li>
</ul>
<h3 id="heading-how-to-set-up-a-d3-environment">How to Set Up a D3 Environment</h3>
<p>D3 works in all modern browsers, and at the time of writing this article, D3.js is on version 7 (v7).</p>
<p>To use the latest version of D3 you have to link to it on your web page like this:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://d3js.org/d3.v7.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>However for the purposes of teaching, all examples in this article are on <a target="_blank" href="https://codepen.io">Codepen</a>, so you can edit the live examples.</p>
<h2 id="heading-how-to-select-elements-in-d3">How to Select Elements in D3</h2>
<p>When you're coding in JavaScript and you need to modify elements on a page, you need to select those elements. D3.js works the same way, and provides us with two methods to select DOM elements:</p>
<ul>
<li><p><code>d3.select()</code></p>
</li>
<li><p><code>d3.selectAll()</code></p>
</li>
</ul>
<p>Both of this selector methods will take in any CSS selector and return the element that matches the specified selector. If no element matches the selector it will return an empty selection.</p>
<p>The <code>d3.select()</code> method will select the first element that matches in the DOM (from top to bottom).</p>
<pre><code class="lang-javascript">d3.select(<span class="hljs-string">"#d3_p"</span>).style(<span class="hljs-string">"color"</span>, <span class="hljs-string">"blue"</span>);

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">cite</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example-text"</span>&gt;</span>Example output<span class="hljs-tag">&lt;/<span class="hljs-name">cite</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_p"</span>&gt;</span> hello world 1<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
</code></pre>
<p>If there are multiple elements that match the specified selector, <a target="_blank" href="http://d3.select"><code>d3.select</code></a><code>()</code> will match the first one it finds.</p>
<pre><code class="lang-javascript">&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"d3_example"</span>&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">cite</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example-text"</span>&gt;</span>Example output<span class="hljs-tag">&lt;/<span class="hljs-name">cite</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_p-all"</span>&gt;</span> hello world 1<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_p-all"</span>&gt;</span> hello world 2<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_p-all"</span>&gt;</span> hello world 3<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_p-all"</span>&gt;</span> hello world 4<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<p>The <code>d3.selectAll()</code> method works very similarly to <a target="_blank" href="http://d3.select"><code>d3.select</code></a><code>()</code> – but instead it selects ALL elements that match the selector:</p>
<pre><code class="lang-javascript">d3.selectAll
(<span class="hljs-string">".d3_p"</span>).style(<span class="hljs-string">"color"</span>, <span class="hljs-string">"blue"</span>);

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">cite</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example-text"</span>&gt;</span>Example output<span class="hljs-tag">&lt;/<span class="hljs-name">cite</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_p"</span>&gt;</span> hello world 1<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_p"</span>&gt;</span> hello world 2<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_p"</span>&gt;</span> hello world 3<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_p"</span>&gt;</span> hello world 4<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
</code></pre>
<h3 id="heading-how-to-modify-elements-in-d3">How to Modify Elements in D3</h3>
<p>After you have selected your DOM elements, D3 provides the following methods to modify them:</p>
<pre><code class="lang-javascript">| Method   |      Usage      |  Example |  
|---|---|---|
| <span class="hljs-string">`.attr()`</span> |  Update selected element attribute | <span class="hljs-string">`d3.select("p").attr("name", "fred")`</span> | 
| <span class="hljs-string">`..classed()`</span> | Assigns or unassigns the specified CSS <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">names</span> <span class="hljs-title">on</span> <span class="hljs-title">the</span> <span class="hljs-title">selected</span> <span class="hljs-title">elements</span>   |   `<span class="hljs-title">d3</span>.<span class="hljs-title">select</span>("<span class="hljs-title">p</span>").<span class="hljs-title">classed</span>("<span class="hljs-title">radio</span>", <span class="hljs-title">true</span>)</span>;<span class="hljs-string">` |
| `</span>.style()<span class="hljs-string">`  | Updates the style property |    `</span>d3.select(<span class="hljs-string">"p"</span>).style(<span class="hljs-string">"color"</span>, <span class="hljs-string">"blue"</span>);<span class="hljs-string">` |
| `</span>.property()<span class="hljs-string">` | Used to set an element property |    `</span>d3.select(<span class="hljs-string">'input'</span>).property(<span class="hljs-string">'value'</span>, <span class="hljs-string">'hello world'</span>)<span class="hljs-string">` |
| `</span>.text()<span class="hljs-string">`  | Updates selected element text content |    `</span>d3.select(<span class="hljs-string">'h1'</span>).text(<span class="hljs-string">'Learning d3.js'</span>)<span class="hljs-string">` |
| `</span>.html()<span class="hljs-string">` | Sets the inner HTML to the specified value on all selected elements |    `</span>d3.select(<span class="hljs-string">'div'</span>).html(<span class="hljs-string">'h1&gt;learning d3.js&lt;/h1&gt;'</span>)<span class="hljs-string">` |
| `</span>.append()<span class="hljs-string">`  | Appends a new element as the last child of the selected element |    `</span>d3.select(<span class="hljs-string">"div"</span>).append(<span class="hljs-string">"p"</span>)<span class="hljs-string">` |
| `</span>.insert()<span class="hljs-string">`  | Works the same as the `</span>.append()<span class="hljs-string">` method, except you can specify another element to insert before |    `</span>d3.select(<span class="hljs-string">"div"</span>).insert(<span class="hljs-string">"p"</span>, <span class="hljs-string">"h1"</span>)<span class="hljs-string">` |
| `</span>.remove()<span class="hljs-string">`  | Removes selected element from the DOM  | `</span>d3.select(<span class="hljs-string">"div"</span>).remove(<span class="hljs-string">"p"</span>)<span class="hljs-string">` |</span>
</code></pre>
<p>Don't worry if all these doesn't make sense right away – we will soon be using all these methods in our examples.</p>
<p>Each of the above DOM manipulation methods takes in a constant value or a function as a parameter which gives rise to creating <strong>Dynamic Properties.</strong></p>
<p>The function takes in two properties: the first is the data which is conventionally called <code>d</code> in d3.js, and the other is the <code>index</code>.</p>
<pre><code class="lang-javascript">d3.selectAll(<span class="hljs-string">"circle"</span>).attr(<span class="hljs-string">'cx'</span>, (<span class="hljs-function">(<span class="hljs-params">d, i</span>) =&gt;</span> i * <span class="hljs-number">100</span>))

&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"d3_example"</span>&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">cite</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example-text"</span>&gt;</span>Example output<span class="hljs-tag">&lt;/<span class="hljs-name">cite</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_svg_demo1"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">g</span> <span class="hljs-attr">transform</span>=<span class="hljs-string">"translate(50, 40)"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">circle</span> <span class="hljs-attr">r</span>=<span class="hljs-string">"30"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">circle</span> <span class="hljs-attr">r</span>=<span class="hljs-string">"30"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">circle</span> <span class="hljs-attr">r</span>=<span class="hljs-string">"30"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">g</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<p>As you can see above, within this function we can apply any logic to manipulate the data and output.</p>
<h2 id="heading-d3-is-data-driven">D3 is Data Driven</h2>
<p>D3.js itself is data-driven, which means it gets its super powers from data. D3 supports different types of data like arrays, CSV, XML, TSV, JSON, and so on.</p>
<p>This data can come from a local file in your working directory or can be fetched from an API.</p>
<h3 id="heading-data-joins-in-d3">Data Joins in D3</h3>
<p>D3's data join lets us join the specified data to the selected element(s). To create a data join, you can use the <code>.data()</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> fruits = [<span class="hljs-string">'Apple'</span>, <span class="hljs-string">'Orange'</span>, <span class="hljs-string">'Mango'</span>]

d3.selectAll(<span class="hljs-string">".d3_fruit"</span>).data(fruits).text(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> d)
</code></pre>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_fruit"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">cite</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example-text"</span>&gt;</span>Example output<span class="hljs-tag">&lt;/<span class="hljs-name">cite</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_fruit"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Let's see what's going on here and why we got only one output instead of three.</p>
<p>So far, we have:</p>
<ol>
<li><p>3 data points in our Fruits Array</p>
</li>
<li><p>1 <code>p</code> element in our selection</p>
</li>
</ol>
<p>D3 just assigns the first fruit (Apple) in our array to the only selection <code>p</code> it got and forgets about the rest.</p>
<p>A quick fix for this is to manually create the other 2 p elements and just move on with your life. But most of the time you don't actually know how many items are in your array of data that is fetched from an external API.</p>
<p>To solve this problem, the latest versions of D3 provides us with a <code>.join()</code> method. It appends, removes, and reorders elements as necessary to match the specified data. Let's try it with our previous example to see what happens:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> fruits = [<span class="hljs-string">'Apple'</span>, <span class="hljs-string">'Orange'</span>, <span class="hljs-string">'Mango'</span>]

d3.select(<span class="hljs-string">".d3_fruit"</span>)
    .selectAll(<span class="hljs-string">"p"</span>)
    .data(fruits)
    .join(<span class="hljs-string">"p"</span>) <span class="hljs-comment">// the join method</span>
        .attr(<span class="hljs-string">"class"</span>, <span class="hljs-string">"d3_fruit"</span>)
        .text(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> d)
</code></pre>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_fruit"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">cite</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example-text"</span>&gt;</span>Example output<span class="hljs-tag">&lt;/<span class="hljs-name">cite</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_fruits"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Let's break this down a bit:</p>
<ol>
<li><p>Select the <code>div</code> wrapper <code>d3_fruit</code></p>
</li>
<li><p>Select all the <code>p</code> elements even when there are no <code>p</code> elements in the div - this returns an empty selection</p>
</li>
<li><p><code>.data(fruits)</code> - Binds the fruits array to the empty selection</p>
</li>
<li><p><code>.join("p")</code> - This methods creates all the <code>p</code> elements for each item in our Array</p>
</li>
<li><p><code>.attr("class", "d3_fruit")</code> - We set a class for each <code>p</code> element that was created</p>
</li>
<li><p><code>.text((d) =&gt; d)</code> - Sets the text of each created <code>p</code> based on the fruits Array</p>
</li>
</ol>
<h3 id="heading-data-loading-in-d3">Data Loading in D3</h3>
<p>We have seen what data is to D3 and how to join data to our selections. But so far we have only used our own self-created data <code>let fruits = ['Apple', 'Orange', 'Mango']</code>.</p>
<p>In a real world scenario this is not usually the case – you sometimes have to fetch data from an API or a local file.</p>
<p>D3 has some methods to load various types of files:</p>
<ul>
<li><p>d3.json</p>
</li>
<li><p>d3.csv</p>
</li>
<li><p>d3.xml</p>
</li>
<li><p>d3.tsv</p>
</li>
<li><p>d3.text</p>
</li>
</ul>
<p>When using any of these methods, the syntax is generally the same:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// async await</span>
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> d3.csv(<span class="hljs-string">"/path/to/file.csv"</span>);
<span class="hljs-built_in">console</span>.log(data);

<span class="hljs-comment">// or</span>
d3.json(<span class="hljs-string">"/path/to/file.json"</span>).then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {  <span class="hljs-built_in">console</span>.log(data); })
</code></pre>
<p>Let's see this in action by loading data from an actual external JSON file.</p>
<p>For this example I have a JSON file that contains all the info about Nigeria and all its states:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> el = d3.select(<span class="hljs-string">"#d3_svg_demo2"</span>);

d3.json(<span class="hljs-string">"https://raw.githubusercontent.com/iamspruce/intro-d3/main/nigeria-states.json"</span>).then(<span class="hljs-function">(<span class="hljs-params">{data}</span>) =&gt;</span> {
    el
     .selectAll(<span class="hljs-string">"p"</span>)
     .data(data)
     .join(<span class="hljs-string">"p"</span>)
      .text(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> d.Name)
});



<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_svg_demo2"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">cite</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example-text"</span>&gt;</span>Example output<span class="hljs-tag">&lt;/<span class="hljs-name">cite</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>    
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>    
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>    
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>    
    ... + 31 others
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
</code></pre>
<p>Using the above method you can fetch any data in D3.</p>
<h2 id="heading-scales-in-d3">Scales in D3</h2>
<p>Thus far, you've learned how to load and use data in D3.js. Now we need to learn about <strong>Scales</strong>. <strong>T</strong>his can be the most confusing part to learn for most folks and it's also the most important concept of D3.</p>
<p>In the last example we just looked at above, we loaded JSON data from an API and for each State in Nigeria we appended the name to a <code>p</code> element. That JSON file also contains the population of each state and some other info.</p>
<p>The population of each state ranges from the lowest at <code>2 million</code> to the highest at <code>16 million</code>. To correctly represent that data on a bar chart, for example, you need to create a bar chart with a height of <code>16000000px</code>.</p>
<p>Just imagining that, you'd probably agree that it would be a very long bar chart. That's where <code>d3.scale</code> comes in.</p>
<p>The <code>d3.scale</code> function takes in data as input and returns a visual value in pixels. <code>d3.scale</code> needs to be set with a <strong>domain</strong> and a <strong>range.</strong> The domain sets a LIMIT for the data we are trying to represent visually.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> x_scale = d3.scaleLinear()
    .domain([<span class="hljs-number">10</span>, <span class="hljs-number">500</span>])
    .range([<span class="hljs-number">2000000</span>, <span class="hljs-number">16000000</span>]);
</code></pre>
<p>Let's break this down a bit:</p>
<ul>
<li><p><code>d3.scaleLinear()</code> - we tell D3 we are going to use the scaleLinear</p>
</li>
<li><p><code>.domain([10, 500])</code> - we set the domain (Limit) from 10 to 500</p>
</li>
<li><p><code>.range([2000000, 16000000])</code> - we set our minimum value to 2 million and maximum to 16 million which means we map out 2 million to <code>10px</code> and 16 million to <code>500px</code></p>
</li>
</ul>
<p>Now if we have a city with a population of about <code>8000000</code>(half of 15 million) it would map out to a pixel value of <code>250px</code>(half of 500).</p>
<p>It is important to point out that D3 has various form of <a target="_blank" href="https://github.com/d3/d3-scale">Scales</a>. The one you decide to use we be determined by the type of data you are trying to represent.</p>
<ul>
<li><p>When you're working with data that represents dates, use <a target="_blank" href="https://github.com/d3/d3-scale#scaleTime">d3.scaleTime</a></p>
</li>
<li><p>When you're creating bar charts, use <a target="_blank" href="https://github.com/d3/d3-scale#scaleBand">d3.scaleBand</a></p>
</li>
<li><p>For other scales, refer to <a target="_blank" href="https://github.com/d3/d3-scale">d3.scale</a></p>
</li>
</ul>
<h2 id="heading-how-to-create-a-bar-chart-with-d3js">How to Create a Bar Chart with D3.js</h2>
<p>Now let's apply everything we've learned to create a real world bar chart with D3.</p>
<p>For this example we are going to continue building from the example code in the data loading section of this tutorial:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> el = d3.select(<span class="hljs-string">"#d3_svg_demo2"</span>);

d3.json(<span class="hljs-string">"https://raw.githubusercontent.com/iamspruce/intro-d3/main/nigeria-states.json"</span>).then(<span class="hljs-function">(<span class="hljs-params">{data}</span>) =&gt;</span> {
    el
     .selectAll(<span class="hljs-string">"p"</span>)
     .data(data)
     .join(<span class="hljs-string">"p"</span>)
      .text(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> d.Name)
});
</code></pre>
<p>First let's create the scales for our bar chart:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> width = <span class="hljs-number">960</span>, height = <span class="hljs-number">500</span>;
<span class="hljs-keyword">const</span> x_scale = d3.scaleBand().range([<span class="hljs-number">0</span>, width])
<span class="hljs-keyword">const</span> y_scale = d3.scaleLinear().range([height, <span class="hljs-number">0</span>])
</code></pre>
<p>What's going on here:</p>
<ul>
<li><p>First we defined our x scale (horizantal scale) with a minimum of 0 and maximum of our SVG width</p>
</li>
<li><p>Secondly we set our y scale (vertical scale) to range from 0 to our SVG height</p>
</li>
</ul>
<p>Next we need to select our SVG element in the document:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> svg = d3.select(<span class="hljs-string">"#d3_demo"</span>)
    .attr(<span class="hljs-string">"width"</span>, width)
    .attr(<span class="hljs-string">"height"</span>, height)
</code></pre>
<p>Here we selected our SVG element and set the height and width to our specified height and width. Next let's fetch the JSON data from our API:</p>
<pre><code class="lang-javascript">d3.json(<span class="hljs-string">"https://raw.githubusercontent.com/iamspruce/intro-d3/main/nigeria-states.json"</span>).then(<span class="hljs-function">(<span class="hljs-params">{ data }</span>) =&gt;</span> {
    data.forEach(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> (d.Population = +d.info.Population))
})
</code></pre>
<p>If this doesn't look familiar please re-read the data loading section. Because of the way our JSON data is structured I destructed <code>{ data }</code> from the API.</p>
<p>The fetched data comes in as a string but we need the Population field to be a number. So using the JavaScript <code>+</code> operator we convert each Population field to a number:</p>
<pre><code class="lang-javascript">data.forEach(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> (d.Population = +d.info.Population))
</code></pre>
<p>Next we need to set the domain of our scales – and now that we have fetched our data we can do that:</p>
<pre><code class="lang-javascript">x_scale.domain(data.map(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> d.Name);
y_scale.domain([<span class="hljs-number">0</span>, d3.max(data, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> d.Population)]);
</code></pre>
<p>Let's see what's going on here:</p>
<ul>
<li><p><code>x_scale.domain(</code><a target="_blank" href="http://data.map"><code>data.map</code></a><code>((d) =&gt;</code> <a target="_blank" href="http://d.Name"><code>d.Name</code></a><code>)</code> - The x scale is a band scale so we set the domain to the name of states (36 states)</p>
</li>
<li><p><code>y_scale.domain([0, d3.max(data, (d) =&gt; d.Population)])</code> - The y scale is a linear scale so we set the minimum value to 0. And rather than setting the maximum value ourselves, we let D3 do that for us by using the <code>d3.max()</code> method.</p>
</li>
</ul>
<p>NOTE: with the <code>d3.max()</code> method we loop through the provided data and always return the maximum value of the specified field (Population in our case).</p>
<p>Lastly we need to add the rectangles so we can see our bar chart:</p>
<pre><code class="lang-javascript">svg
 .selectAll(<span class="hljs-string">"rect"</span>)
 .data(data)
 .join(<span class="hljs-string">"rect"</span>)
  .attr(<span class="hljs-string">"class"</span>, <span class="hljs-string">"bar"</span>)
  .attr(<span class="hljs-string">"x"</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> x_scale(d.Name))
  .attr(<span class="hljs-string">"y"</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> y_scale(d.Population))
  .attr(<span class="hljs-string">"width"</span>, x_scale.bandwidth())
  .attr(<span class="hljs-string">"height"</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> height - y_scale(d.Population));
</code></pre>
<p>Okay this isn't something new right? If this is still new please re-read the data join section of this tutorial. But there are some things we are seeing for the first time:</p>
<ul>
<li><p><code>.attr("x", (d) =&gt; x_scale(</code><a target="_blank" href="http://d.Name"><code>d.Name</code></a><code>))</code> - We set the x (horizontal) position of each <code>rect</code> created according to the generated scale. Same for the y (vertical position <code>.attr("y", (d) =&gt; y_scale(d.Population))</code>.</p>
</li>
<li><p><code>.attr("width", x_scale.bandwidth())</code> - here we set the width of each <code>rect</code>. Of course we can set this to any number we like, but using <code>x_scale.bandwidth()</code> D3 automatically sizes the <code>rect</code> for us to match the width of our SVG.</p>
</li>
<li><p><code>.attr("height", (d) =&gt; height - y_scale(d.Population))</code> - lastly we set the height of each <code>rect</code> to the SVG height and then subtract the height generated by the <code>y_scale(d.Population)</code>, making sure each <code>rect</code> is represented correctly.</p>
</li>
</ul>
<p>Here is the full code put together in one place:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> width = <span class="hljs-number">960</span>, height = <span class="hljs-number">500</span>;

<span class="hljs-keyword">const</span> x_scale = d3.scaleBand().range([<span class="hljs-number">0</span>, width]).padding(<span class="hljs-number">0.1</span>);
<span class="hljs-keyword">const</span> y_scale = d3.scaleLinear().range([height, <span class="hljs-number">0</span>]);

<span class="hljs-keyword">const</span> svg = d3.select(<span class="hljs-string">"#d3_demo"</span>)
    .attr(<span class="hljs-string">"width"</span>, width)
    .attr(<span class="hljs-string">"height"</span>, height);

d3.json(<span class="hljs-string">"https://raw.githubusercontent.com/iamspruce/intro-d3/main/nigeria-states.json"</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">{ data }</span>) =&gt;</span> {

     data.forEach(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> (d.Population = +d.info.Population));

     <span class="hljs-comment">// Scale the Domain</span>
     x_scale.domain(data.map(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> d.Name));
     y_scale.domain([<span class="hljs-number">0</span>, d3.max(data, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> d.Population)]);

     <span class="hljs-comment">// add the rectangles for the bar chart</span>
     svg
      .selectAll(<span class="hljs-string">"rect"</span>)
      .data(data)
      .join(<span class="hljs-string">"rect"</span>)
      .attr(<span class="hljs-string">"class"</span>, <span class="hljs-string">"bar"</span>)
      .attr(<span class="hljs-string">"x"</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> x_scale(d.Name))
      .attr(<span class="hljs-string">"y"</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> y_scale(d.Population))
      .attr(<span class="hljs-string">"width"</span>, x_scale.bandwidth())
      .attr(<span class="hljs-string">"height"</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> height - y_scale(d.Population));
    });
</code></pre>
<p>And here's the output:</p>
<pre><code class="lang-javascript">%[https:<span class="hljs-comment">//codepen.io/Spruce_khalifa/pen/porxVVd]</span>
</code></pre>
<p>And there you have it, a very basic D3.js bar chart. But if you showed that bar chart to a colleague or friend, they would probably ask you "what's going on here, what are we looking at?" That would lead us to another topic – the <strong>Axis</strong>.</p>
<h3 id="heading-axis-component-in-d3">Axis Component in D3</h3>
<blockquote>
<p>The axis component renders human-readable reference marks for scales. – D3 docs</p>
</blockquote>
<p>To create these human readable reference marks, the <code>d3.axis</code> makes uses the <code>d3.scale</code> function to determine the number of ticks to generate.</p>
<p>To create different orientations for our axis, D3 provides four methods:</p>
<ul>
<li><p>d3.axisTop</p>
</li>
<li><p>d3.axisBottom</p>
</li>
<li><p>d3.axisLeft</p>
</li>
<li><p>d3.axisRight</p>
</li>
</ul>
<p>Let's see an example of these:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> svg = d3.select(<span class="hljs-string">"#d3_demo8"</span>).attr(<span class="hljs-string">'width'</span>, <span class="hljs-number">200</span>).attr(<span class="hljs-string">'height'</span>, <span class="hljs-number">200</span>)
<span class="hljs-keyword">let</span> scale = d3.scaleLinear().domain([<span class="hljs-number">0</span>, <span class="hljs-number">100</span>]).range([<span class="hljs-number">0</span>, <span class="hljs-number">200</span>]);


<span class="hljs-keyword">let</span> bottom_axis = d3.axisBottom(scale);

svg.append(<span class="hljs-string">"g"</span>).call(bottom_axis);
</code></pre>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_demo"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example d3_no_pad"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_svg_demo2"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">cite</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"d3_example-text"</span>&gt;</span>Example output<span class="hljs-tag">&lt;/<span class="hljs-name">cite</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_demo8"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>To make all this work, you only need to pass in your existing <code>d3.scale</code> function. Let's apply this to our previous example.</p>
<p>The first thing we need to do is to set up the D3 margin convention.</p>
<h3 id="heading-d3-margin-convention">D3 Margin Convention</h3>
<p>The margin convention is just a way of adding margins to our graphics so as to have space to add our Axis.</p>
<p>To create the margin, first create an object with a property for each of the four sides:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> margin = { <span class="hljs-attr">top</span>: <span class="hljs-number">20</span>, <span class="hljs-attr">right</span>: <span class="hljs-number">30</span>, <span class="hljs-attr">bottom</span>: <span class="hljs-number">55</span>, <span class="hljs-attr">left</span>: <span class="hljs-number">70</span> }
</code></pre>
<p>Then you need to define the width and height for our SVG. For a responsive graphic we set the width to the document body:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> width = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"body"</span>).clientWidth;
<span class="hljs-keyword">const</span> height = <span class="hljs-number">500</span>;
</code></pre>
<p>Next we need to apply this width as a view box to our SVG element:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> svg = d3.select(<span class="hljs-string">"#d3_demo"</span>).attr(<span class="hljs-string">"viewBox"</span>, [<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, width, height])
</code></pre>
<p>Next we need to set the <code>x_scale</code> and <code>y_scale</code> to work with our new margins:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> x_scale = d3
    .scaleBand()
    .range([margin.left, width - margin.right])
    .padding(<span class="hljs-number">0.1</span>);

<span class="hljs-keyword">const</span> y_scale = d3.scaleLinear()
    .range([height - margin.bottom, margin.top]);
</code></pre>
<p>Next let's define our left and bottom axis – remember we only need to pass in our existing scale (the ones above):</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> x_axis = d3.axisBottom(x_scale);

<span class="hljs-keyword">let</span> y_axis = d3.axisLeft(y_scale);
</code></pre>
<p>Everything else is the same as our previous example except the last part where we add the Axis:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// append x axis</span>
svg
 .append(<span class="hljs-string">"g"</span>)
  .attr(<span class="hljs-string">"transform"</span>, <span class="hljs-string">`translate(0,<span class="hljs-subst">${height - margin.bottom}</span>)`</span>)
  .call(x_axis)
  .selectAll(<span class="hljs-string">"text"</span>) <span class="hljs-comment">// everything from this point is optional</span>
  .style(<span class="hljs-string">"text-anchor"</span>, <span class="hljs-string">"end"</span>)
  .attr(<span class="hljs-string">"dx"</span>, <span class="hljs-string">"-.8em"</span>)
  .attr(<span class="hljs-string">"dy"</span>, <span class="hljs-string">".15em"</span>)
  .attr(<span class="hljs-string">"transform"</span>, <span class="hljs-string">"rotate(-65)"</span>);

<span class="hljs-comment">// add y axis</span>
svg
 .append(<span class="hljs-string">"g"</span>)
  .attr(<span class="hljs-string">"transform"</span>, <span class="hljs-string">`translate(<span class="hljs-subst">${margin.left}</span>,0)`</span>)
  .call(y_axis);
</code></pre>
<p>You can view the <a target="_blank" href="https://codepen.io/Spruce_khalifa/pen/RwZvOPx">output and full code on Codepen</a>.</p>
<h3 id="heading-how-to-style-it-with-css-in-d3">How to Style it With CSS in D3</h3>
<p>You'll notice that our bar chart is green in color – how come? Well, we added a class of <code>bar</code> to each bar in the chart:</p>
<pre><code class="lang-javascript">.attr(<span class="hljs-string">"class"</span>, <span class="hljs-string">"bar"</span>)
</code></pre>
<p>We can use that class to style our bar chart with CSS:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.bar</span> {
  <span class="hljs-attribute">fill</span>: green;
}
</code></pre>
<h2 id="heading-how-to-create-a-world-map-with-d3js">How to Create a World Map With D3.js</h2>
<p>One of the things I personally love about D3 is its ability to handle geographic data. Unlike our former examples, which used JSON data format maps, now we'll use a special form of JSON data called <a target="_blank" href="http://geojson.org/">GeoJSON</a>.</p>
<p>You can find the GeoJSON data we are going to use <a target="_blank" href="https://raw.githubusercontent.com/iamspruce/intro-d3/main/data/countries-110m.geojson">here</a>.</p>
<p>Like in our other examples, let's first select our SVG element in the document and also set up <strong>the margin convention:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> margin = { <span class="hljs-attr">top</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">right</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">bottom</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">left</span>: <span class="hljs-number">5</span> },
    width = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"body"</span>).clientWidth,
    height = <span class="hljs-number">500</span>;

<span class="hljs-keyword">const</span> svg = d3.select(<span class="hljs-string">"#d3_demo"</span>).attr(<span class="hljs-string">"viewBox"</span>, [<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, width, height]);
</code></pre>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_demo"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>Next, to generate our map we'll need a projection to render spherical coordinates (in our data file) and a Path Generator to convert the projected coordinates to a SVG path which is then rendered on the screen:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> projection = d3.geoEquirectangular().center([<span class="hljs-number">0</span>, <span class="hljs-number">0</span>]);
</code></pre>
<p>D3 provides a lot of <a target="_blank" href="https://github.com/d3/d3-geo-projection">projections</a> (I only used this one because I like it). Now that we have chosen our projection, let's convert it to an SVG path. D3 handles the conversion for us when we use the <code>d3.geoPath()</code> method. This method takes in a projection (the one we defined above):</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> pathGenerator = d3.geoPath().projection(projection);
</code></pre>
<p>We don't want to draw the map directly on the SVG because we are going to be adding animations and zooming later on. So we append a <code>g</code> element to the selected SVG:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> g = svg.append(<span class="hljs-string">"g"</span>);
</code></pre>
<p>Then we'll load our data for the map:</p>
<pre><code class="lang-javascript">d3.json(<span class="hljs-string">"https://raw.githubusercontent.com/iamspruce/intro-d3/main/data/countries-110m.geojson"</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(data)
  });
</code></pre>
<p>If this doesn't make sense I suggest you re-read the data loading section.</p>
<p>Lastly let's use our <code>pathGenerator</code> to generate our paths:</p>
<pre><code class="lang-javascript"> g.selectAll(<span class="hljs-string">"path"</span>)
    .data(data.features)
    .join(<span class="hljs-string">"path"</span>)
    .attr(<span class="hljs-string">"d"</span>, pathGenerator);
</code></pre>
<p>Above we used D3 data join to append a path for each country and then set the <code>d</code> attribute to our <code>pathGenerator</code>:</p>
<pre><code class="lang-javascript">.attr(<span class="hljs-string">"d"</span>, pathGenerator);
</code></pre>
<p>And in case that isn't clear, it's the equivalent of writing this:</p>
<pre><code class="lang-javascript">.attr(<span class="hljs-string">'d'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> pathGenerator(d))
</code></pre>
<p>You can find the <a target="_blank" href="https://codepen.io/Spruce_khalifa/pen/dyzLyxp">final code and live preview on Codepen</a>.</p>
<h3 id="heading-how-to-use-multiple-datasets-in-d3js">How to Use Multiple Datasets in D3.js</h3>
<p>Sometimes you'll want to visualize two datasets from different sources. For example I have a data <a target="_blank" href="https://github.com/iamspruce/intro-d3/blob/main/data/nigeria_state_boundaries.geojson">file</a> that contains the geographic data of Nigeria and another <a target="_blank" href="https://github.com/iamspruce/intro-d3/blob/main/data/nigeria-states.json">file</a> that contains information about states in Nigeria.</p>
<p>In the data loading section of this tutorial, we only covered loading a single data set. Loading multiple datasets in D3 looks like this:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Promise</span>.all([
    d3.json(<span class="hljs-string">"https://raw.githubusercontent.com/iamspruce/intro-d3/main/data/nigeria_state_boundaries.geojson"</span>),
    d3.json(<span class="hljs-string">"https://raw.githubusercontent.com/iamspruce/intro-d3/main/data/nigeria-states.json"</span>)
]).then(<span class="hljs-function">(<span class="hljs-params">[geoJSONdata, countryData]</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(geoJSONdata)
    <span class="hljs-built_in">console</span>.log(countryData)
});
</code></pre>
<p>By adding all the D3 data loading methods <code>d3.json()</code> inside the <code>Promise.all</code>, the <code>.then()</code> callback will only get called when all the data have finished loading, although if one of the data file fails to load the callback will not be called and would result in an error.</p>
<h3 id="heading-map-with-city-names">Map with City Names</h3>
<p>Now let's use the <strong>loading multiple datasets</strong> idea to create a map with city names.</p>
<p>For simplicity we are going to leave out the part of creating the map because we already covered that above. Now, we'll only focus on adding the cities names:</p>
<p>Once we have loaded the data we need to format it:</p>
<pre><code class="lang-javascript">countryData.data.forEach(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> {
 d.info.Longitude = +d.info.Longitude;
 d.info.Latitude = +d.info.Latitude;
});
</code></pre>
<p>Above we converted the longitudes and latitudes. Next we need to fit our map to our container. To do that you'll use the <code>d3.fitSize()</code> method:</p>
<pre><code class="lang-javascript">projection.fitSize([width, height], geoJSONdata);
</code></pre>
<p>Lastly we need to add the city names:</p>
<pre><code class="lang-javascript">g.selectAll(<span class="hljs-string">"text"</span>)
 .data(countryData.data)
 .join(<span class="hljs-string">"text"</span>)
  .attr(<span class="hljs-string">"x"</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> projection([d.info.Longitude, d.info.Latitude])[<span class="hljs-number">0</span>])
  .attr(<span class="hljs-string">"y"</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> projection([d.info.Longitude, d.info.Latitude])[<span class="hljs-number">1</span>])
  .attr(<span class="hljs-string">"dy"</span>, <span class="hljs-number">-7</span>)
  .style(<span class="hljs-string">"fill"</span>, <span class="hljs-string">"black"</span>)
  .attr(<span class="hljs-string">"text-anchor"</span>, <span class="hljs-string">"middle"</span>)
  .text(<span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> d.Name);
</code></pre>
<p>And that's it! We have a map with name of cities (I might have added circles too, because I think it's cool). The <a target="_blank" href="https://codepen.io/Spruce_khalifa/pen/BadEywO">full code is on Codepen</a>.</p>
<h2 id="heading-event-handling-with-d3js">Event Handling with D3.js</h2>
<p>At the beginning of this tutorial we talked about selections, but one thing we didn't cover was event handling.</p>
<p>In D3 we can add or remove event handlers to or from selected document elements using the <code>.on()</code> method.</p>
<p>The <code>.on()</code> method accepts two arguments:</p>
<ol>
<li><p>Event type (usually a string)</p>
</li>
<li><p>A callback function that is called when our event is fired</p>
</li>
</ol>
<h3 id="heading-event-types-in-d3">Event Types in D3</h3>
<p>The D3 <code>.on()</code> event type can be any <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Events#Standard_events">DOM event type</a>, but the most common events with D3 are:</p>
<pre><code class="lang-javascript">| Event Type  | Description  |
|---|---|
| zoom  | selection is being panned and zoomed  |
| click  | selection got clicked  |
| mouseover  | mouse pointer moves over a selection  |
| mouseout  | mouse pointer leaves a slection  |
</code></pre>
<h3 id="heading-map-with-panning-and-zooming">Map with Panning and Zooming</h3>
<p>To see how D3 event handling works let's add pan and zoom to our previously created map.</p>
<p>The first thing we need to do is to define the zoom function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> zooming = d3
  .zoom()
  .scaleExtent([<span class="hljs-number">1</span>, <span class="hljs-number">8</span>])
  .on(<span class="hljs-string">"zoom"</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(event)
  })
</code></pre>
<p>Then the next thing we need to do is use the <code>d3.zoom()</code> method. We also set the <code>scaleExtent([1,8])</code>. We do this to set the limit of the zoom, otherwise you'll keep zooming to infinity. Now let's add the transformation to our map paths in the callback function:</p>
<pre><code class="lang-javascript">.on(<span class="hljs-string">"zoom"</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-comment">// transform paths when zoomed</span>
  g.selectAll(<span class="hljs-string">"path"</span>).attr(<span class="hljs-string">"transform"</span>, event.transform);

  <span class="hljs-comment">// transform circles when zoomed</span>
  g.selectAll(<span class="hljs-string">"circle"</span>)
    .attr(<span class="hljs-string">"transform"</span>, event.transform)
    .attr(<span class="hljs-string">"r"</span>, <span class="hljs-number">5</span> / event.transform.k);

  <span class="hljs-comment">// transform text when zoomed</span>
  g.selectAll(<span class="hljs-string">"text"</span>)
    .attr(<span class="hljs-string">"transform"</span>, event.transform)
    .style(<span class="hljs-string">"font-size"</span>, <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-number">18</span> / event.transform.k}</span>`</span>)
    .attr(<span class="hljs-string">"dy"</span>, <span class="hljs-number">-7</span> / event.transform.k);
});
</code></pre>
<p>NOTE: The <code>event.transform</code> is a short hand for setting the <code>translate('x','y')</code> and <code>scale</code> (event.transform.k).</p>
<p>Lastly let's call the zooming function on our SVG selection:</p>
<pre><code class="lang-javascript">svg.call(zooming)
</code></pre>
<p>You can find the <a target="_blank" href="https://codepen.io/Spruce_khalifa/pen/MWvROBq">full code and preview on Codepen</a>.</p>
<h3 id="heading-programmatic-zooming-in-d3">Programmatic zooming in D3</h3>
<p>Turns out in D3 we can control zooming programmatically, this let us create buttons that can be used to control the zoom behavior:</p>
<p>Let's add those buttons to our previous map:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
 <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn-group-vertical"</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"group"</span> <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"..."</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"float-button-group"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn-default"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"zoomIn"</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"svg-icon"</span> <span class="hljs-attr">viewBox</span>=<span class="hljs-string">"0 0 20 20"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Zoom In<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    ...svg icon
    <span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn-default"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"zoomOut"</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"svg-icon"</span> <span class="hljs-attr">viewBox</span>=<span class="hljs-string">"0 0 20 20"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Zoom Out<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  ...svg icon
    <span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn-default"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"resetZoom"</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"svg-icon"</span> <span class="hljs-attr">viewBox</span>=<span class="hljs-string">"0 0 20 20"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Reset Zoom<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    ...svg icon
    <span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"d3_demo"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>The next step is to select those buttons and control the zoom behavior:</p>
<pre><code class="lang-javascript">d3.select(<span class="hljs-string">"#zoomIn"</span>).on(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  svg.transition().call(zooming.scaleBy, <span class="hljs-number">2</span>);
});
d3.select(<span class="hljs-string">"#zoomOut"</span>).on(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  svg.transition().call(zooming.scaleBy, <span class="hljs-number">0.5</span>);
});
d3.select(<span class="hljs-string">"#resetZoom"</span>).on(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  svg.transition().call(zooming.scaleTo, <span class="hljs-number">1</span>);
});
</code></pre>
<p>What is <code>scaleBy</code> and <code>scaleTo</code>? <code>scaleBy</code> multiplies the current scale by our given value (2), while <code>scaleTo</code> sets the scale factor to our given value (1) which resets the zoom.</p>
<p>You can find the <a target="_blank" href="https://codepen.io/Spruce_khalifa/pen/eYEoyYo">preview and full code on Codepen</a>.</p>
<h3 id="heading-how-to-add-tooltips-in-d3">How to Add ToolTips in D3</h3>
<p>Let's add ToolTips to our map. A tooltip shows more information about an item when the user hovers over that item.</p>
<p>Let's first create the tooltip:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> tooltip = d3
  .select(<span class="hljs-string">"body"</span>)
  .append(<span class="hljs-string">"div"</span>)
  .attr(<span class="hljs-string">"class"</span>, <span class="hljs-string">"tooltip"</span>)
  .style(<span class="hljs-string">"opacity"</span>, <span class="hljs-number">0</span>);
</code></pre>
<p>Next let's add the tooltip when the circle is hovered over, and remove it when the mouse pointer leaves the circle:</p>
<pre><code class="lang-javascript">g.selectAll(<span class="hljs-string">"circle"</span>)
  ...
  .style(<span class="hljs-string">"fill"</span>, <span class="hljs-string">"green"</span>)
  .on(<span class="hljs-string">"mouseover"</span>, <span class="hljs-function">(<span class="hljs-params">event, d</span>) =&gt;</span> {
    tooltip.transition().duration(<span class="hljs-number">200</span>).style(<span class="hljs-string">"opacity"</span>, <span class="hljs-number">0.9</span>);
    tooltip.html(<span class="hljs-string">`&lt;p&gt;Population: <span class="hljs-subst">${d.info.Population}</span>&lt;/a&gt;`</span> + <span class="hljs-string">`&lt;p&gt;Name: <span class="hljs-subst">${d.Name}</span>&lt;/p&gt;`</span>)
    .style(<span class="hljs-string">"left"</span>, event.pageX + <span class="hljs-string">"px"</span>)
    .style(<span class="hljs-string">"top"</span>, event.pageY - <span class="hljs-number">28</span> + <span class="hljs-string">"px"</span>);
  })
  .on(<span class="hljs-string">"mouseout"</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =&gt;</span> {
    tooltip.transition().duration(<span class="hljs-number">500</span>).style(<span class="hljs-string">"opacity"</span>, <span class="hljs-number">0</span>);
  });
</code></pre>
<p>Here's the <a target="_blank" href="https://codepen.io/Spruce_khalifa/pen/mdMYEBJ">final code and preview</a> (try hovering on the circles):</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Congratulations D3 Ninja! You've made it this far. Hopefully you have learnt the basics of Data Visualization with D3.</p>
<p>Here are some next steps:</p>
<ul>
<li><p>Check out the <a target="_blank" href="https://www.freecodecamp.org/learn/data-visualization/">freeCodeCamp Data Visualization</a> certification</p>
</li>
<li><p>Check out the docs and more on <a target="_blank" href="https://d3js.org/">D3's officail website</a></p>
</li>
</ul>
<p>If you created something wonderful with this, please feel free to tweet about it and tag me <a target="_blank" href="https://twitter.com/sprucekhalifa">@sprucekhalifa</a>. And don't forget to hit the follow button.</p>
<p>Oh and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Charting the waters (pt. 2): a comparison of JavaScript charting libraries ]]>
                </title>
                <description>
                    <![CDATA[ By Mandi Cai A deep dive into D3.js, Dygraphs, Chart.js, and Google Charts The code for the charts I created in the header image is up on GitHub. When I began creating charts and visualizing data, the only things I knew were “Consider Canvas for lar... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/charting-the-waters-pt-2-a-comparison-of-javascript-charting-libraries-96e9fb79b856/</link>
                <guid isPermaLink="false">66c3473793db2451bd44142e</guid>
                
                    <category>
                        <![CDATA[ D3.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data visualization ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 24 Jan 2019 17:35:00 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*sOgqVGUuzDv1O8HtWw8wFA.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Mandi Cai</p>
<h4 id="heading-a-deep-dive-into-d3js-dygraphs-chartjs-and-google-charts">A deep dive into D3.js, Dygraphs, Chart.js, and Google Charts</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*sOgqVGUuzDv1O8HtWw8wFA.png" alt="Image" width="800" height="450" loading="lazy"></p>
<p>The code for the charts I created in the header image is up on <a target="_blank" href="https://github.com/mandicai/boscc-charts">GitHub</a>.</p>
<p>When I began creating charts and visualizing data, the only things I knew were “Consider <a target="_blank" href="https://canvasjs.com/">Canvas</a> for large datasets” and “<a target="_blank" href="https://d3js.org/">D3</a> is magic”. I had no idea that there existed an entire ecosystem of charting libraries. These libraries are free, available, and complete with examples and documentation.</p>
<p>More importantly, each library has its own pros and cons with regards to the variety of charts, learning curve, level of customization, and out-of-the-box interactivity. So how does one decide?</p>
<p>I’ll compare a few popular JavaScript charting libraries in this article, specifically <a target="_blank" href="https://d3js.org/"><strong>D3.js</strong></a><strong>, <a target="_blank" href="http://dygraphs.com/">Dygraphs</a></strong>, <a target="_blank" href="https://www.chartjs.org/">Chart.js</a>, and <a target="_blank" href="https://developers.google.com/chart/"><strong>Google Charts</strong></a>. Expect to learn how to create a JavaScript chart, a high-level comparison across libraries of the aforementioned factors (variety of charts, customization, etc.), and the use case I perceive to be best suited to each charting library.</p>
<p>But first, a quick introduction to why visualizing data is becoming increasingly important. You’re welcome to skip to the side-by-side comparison (<code>Ctrl+F</code> “Let’s compare!”).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*nb6xvXcMDMDhEM0Z" alt="Image" width="800" height="609" loading="lazy"></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*ZhBuvIhsgEOET25q" alt="Image" width="794" height="890" loading="lazy"></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*_pP_224BUyY5ZhEY" alt="Image" width="800" height="611" loading="lazy">
_Source: [Wait But Why](https://www.nytimes.com/interactive/2018/08/04/upshot/up-birth-age-gap.html" rel="noopener" target="_blank" title=""&gt;The Upshot, <a href="http://rhythm-of-food.net/" target="_blank">The Rhythm of Food</a>, and &lt;a href="https://waitbutwhy.com/2016/01/horizontal-history.html" rel="noopener" target="<em>blank" title=")</em></p>
<h3 id="heading-why-chart-and-visualize-data"><strong>Why chart and visualize data?</strong></h3>
<p>I’ve always thought of data visualizations as a better way to <strong>learn</strong> and <strong>engage</strong> an audience. Not everyone is a natural at absorbing information through text. My eyes glaze over when trying to extract numbers from a block of words. Text also assumes you’re familiar with the language it’s written in. I struggled with textbook readings in college. It’s plausible that non-native English speakers were having a hard time as well.</p>
<p>Alternatively, whenever I came across a beautiful, clarifying diagram amidst the piles of information, I immediately grasped the concepts and remembered them better too.</p>
<p>Our minds are not wired to quickly and thoroughly understand large chunks of text or piles of Excel rows. But what they do excel at is recognizing similarity, symmetry, connections between objects, and continuity, which are foundations of data visualization. Think Gestalt Principles.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*6mBvVtXeImAn7u9KM3MMQg.jpeg" alt="Image" width="597" height="323" loading="lazy">
_Gestalt Principles (Source: [FusionCharts](https://www.fusioncharts.com/blog/how-to-use-the-gestalt-principles-for-visual-storytelling-podv/" rel="noopener" target="<em>blank" title="))</em></p>
<p>Here’s a snippet of some data from the <a target="_blank" href="https://www.bls.gov/lau/#tables">Bureau of Labor Statistics</a> about the unemployment rates across U.S. counties (represented by a FIPS code) in 2016.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*U_fs8Blf5QypSWvE6Phq3Q.png" alt="Image" width="800" height="581" loading="lazy">
_Source: [Bureau of Labor Statistics](https://www.bls.gov/lau/#tables" rel="noopener" target="<em>blank" title=")</em></p>
<p>To spot trends or catch outliers, the average person would spend a significant amount of time staring at this data. They may scan each row and re-write figures on another sheet of paper. Not ideal.</p>
<p>But if we visualize the data as a geographic map, as Mike Bostock did in his <a target="_blank" href="https://beta.observablehq.com/@mbostock/d3-choropleth">Observable notebook</a>:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*u9tFdrMr4u-gLJqU" alt="Image" width="800" height="494" loading="lazy">
_Source: [D3 Chloropleth](https://beta.observablehq.com/@mbostock/d3-choropleth" rel="noopener" target="<em>blank" title=")</em></p>
<p>You can immediately see hotspots for higher unemployment. Instead of hours, you’ve now detected interesting patterns in <strong>seconds.</strong> That difference in time to understand can mean the difference between ditching a seemingly “incomprehensible” dataset, or alternatively, <em>furthering your investigation</em>. Creating accurate and accessible visualizations also allows viewers to catch inconsistencies or holes in the dataset, which <strong>holds the data more accountable</strong>.</p>
<h3 id="heading-the-anatomy-of-a-chart"><strong>The anatomy of a chart</strong></h3>
<p>Before jumping into the library comparison, I think the basic “anatomy” of a JavaScript chart warrants an overview. While working through these libraries, I noticed that all except for D3* adopted the same pattern for generating charts.</p>
<ol>
<li>Import the charting library into the HTML.</li>
<li>Create a <code>&lt;d</code>iv&gt; with an ID identifier, such as “my-first-chart”.</li>
<li>Fetch and load data in the JS. You may also define the data directly in the JS. Make sure you’ve linked this JS file in the HTML.</li>
<li>Pass the data, the <code>&lt;d</code>iv&gt; container, and an options object to a chart generator function.</li>
<li>Some libraries, like Google Charts, require calling <code>draw()</code> to draw the generated chart.</li>
<li>Serve the code up on a Python server with <code>http-server -c-1 -p 8000</code> and see your first chart at <code>localhost:8000</code>.</li>
</ol>
<p><strong>Examples</strong></p>
<ul>
<li><a target="_blank" href="http://dygraphs.com/tutorial.html">Basic Dygraphs example</a></li>
<li><a target="_blank" href="http://bl.ocks.org/d3noob/b3ff6ae1c120eea654b5">Basic D3.js example</a></li>
<li><a target="_blank" href="https://www.chartjs.org/docs/latest/">Basic Chart.js example</a></li>
<li><a target="_blank" href="https://developers.google.com/chart/interactive/docs/quick_start">Basic Google Charts example</a></li>
</ul>
<p>*D3 has been primarily used for charting, but it’s more of a collection of toolkits than your standard charting library. See <a target="_blank" href="https://medium.com/@mbostock/why-you-should-use-d3-ae63c276e958">this article</a> for a better explanation.</p>
<h3 id="heading-lets-compare"><strong>Let’s compare!</strong></h3>
<p>When picking any library, I like to start with these evaluation questions:</p>
<ul>
<li>What’s the learning curve? (quality of documentation, code complexity)</li>
<li>How much can I customize my charts?</li>
<li>Is the library actively supported?</li>
<li>What types of data does this library take?</li>
<li>What modes of interactivity are offered?</li>
<li>Does the library offer responsive charts?</li>
</ul>
<h3 id="heading-learning-curve"><strong>Learning curve</strong></h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*dgKyUbyk0tJAnZuMvflftw.png" alt="Image" width="800" height="117" loading="lazy"></p>
<p>Dygraphs, Chart.js, and Google Charts have relatively small learning curves. They are great if you need to whip up charts in a couple of hours.</p>
<p>D3 has the highest learning curve, and the reason for this is the fine-grain, low-level control it offers. It’s more of a well-written library of advanced helper functions. D3 can theoretically be used in conjunction with other charting libraries.</p>
<p>To explore a bit further, I created the same chart across all 4 libraries using Boston weather data from <a target="_blank" href="https://www.meteoblue.com/en/weather/forecast/week/boston_united-states-of-america_4930956">meteoblue</a>. The code is up on <a target="_blank" href="https://github.com/mandicai/boscc-charts">GitHub</a>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*LEm2V03A5QWMO5e47ahWtw.png" alt="Image" width="800" height="450" loading="lazy">
<em>Top row: D3, Dygraphs, Bottom row: Chart.js, Google Charts</em></p>
<p>…. and recorded the lines of code needed to make each chart:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*OUK3WpJ8DQW8Hh4vh8XGqQ.png" alt="Image" width="800" height="120" loading="lazy"></p>
<p>The lines of code support the original comparison of learning curves. D3 needs significantly more lines to get a basic chart up and running but provides more opportunity for customization.</p>
<h3 id="heading-customization"><strong>Customization</strong></h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*lwbxOc-JhaKcvIrbUJuigQ.png" alt="Image" width="800" height="96" loading="lazy"></p>
<p>D3 shines in the customization arena. D3’s granularity and modularity is exactly why designers and developers favor it as the medium for stunning and unique visualizations. <a target="_blank" href="https://www.chartjs.org/docs/latest/configuration/">Chart.js</a> and <a target="_blank" href="https://developers.google.com/chart/interactive/docs/customizing_charts">Google Charts</a> offer numerous options that can be passed into a generator function, such as legend font size and thickness of a line.</p>
<h3 id="heading-active-development"><strong>Active development</strong></h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*iFA6LDP2UzQokxhM9d_Jog.png" alt="Image" width="800" height="113" loading="lazy"></p>
<p>I define library development as the frequency of releases and the responsiveness of library maintainers to opened issues and feedback for improvement. A supportive and large community of users is also a plus. Usage encourages healthy change and accountability as the JavaScript ecosystem evolves.</p>
<p>Looking at the respective GitHub repositories, I discovered releases and resolved issues for Dygraphs and Google Charts to be more sporadic than D3 and Chart.js. D3 will not reach a halt in development any time soon. Its creator and contributors recently released a major version (v5.0) in 2018. They still actively contribute to the visualization community. Chart.js’s latest release also occurred pretty recently in 2018. The release addressed issues and enhancements. They are documented thoroughly in the release notes.</p>
<h3 id="heading-types-of-data"><strong>Types of data</strong></h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*4eaY8zfk3cQmnCagiTWSXw.png" alt="Image" width="800" height="139" loading="lazy"></p>
<p>This speaks for itself. Fun fact: I used D3’s <a target="_blank" href="https://github.com/d3/d3-fetch">fetch library</a> to fetch data. I used other libraries to chart it. D3 has fetch functions for almost all common data formats used in data visualization.</p>
<h3 id="heading-interactivity"><strong>Interactivity</strong></h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*L8m_dlLsbGHUrEytWwKakA.png" alt="Image" width="800" height="104" loading="lazy"></p>
<p>Dygraphs, Chart.js, and Google Charts all have some out-of-box interactivity features, like tool tips, zoom, and events. It’s difficult to introduce highly custom interactions because each library is so encapsulated. With D3, you accept that complicated and unique interactions are possible. The tradeoff is simple interactions, like a tool tip, must also be constructed from the ground up.</p>
<h3 id="heading-responsiveness"><strong>Responsiveness</strong></h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*RT1nSrhty8S5VSOrMpPF4A.png" alt="Image" width="800" height="144" loading="lazy"></p>
<p>Chart.js and D3 offer responsive charts out of the box (for D3, specify a <code>viewBox</code> instead of <code>width</code> and <code>height</code> for the <code>svg</code> container). Dygraphs and Google Charts need some additional work to create responsive charts, like adding <code>position: relative</code> to the chart container or redrawing the chart on <code>$(window).resize()</code>.</p>
<p><a target="_blank" href="http://dygraphs.com/tests/resize.html">Dygraphs responsive char</a>t (inspect the chart containers to see the CSS classes)</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/8950761/google-chart-redraw-scale-on-window-resize">Responsive Google Charts Stack Overflow thread</a></p>
<h3 id="heading-best-used-for"><strong>Best used for?</strong></h3>
<p>Last but not least, I’ve listed the use case that I think each library is best suited for:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*l0EZD0RSsxBzOw9stODUVA.png" alt="Image" width="800" height="301" loading="lazy">
<em>All screenshots taken from each library’s respective examples section</em></p>
<p>D3 is worth investing time in if you <strong>a) need a highly custom visualization</strong> and/or <strong>b) want helper functions to use in conjunction with other libraries.</strong></p>
<p>I enjoyed Dygraphs for time series because the user can pan over the series and <strong>see the date and corresponding point by default</strong>. You can also <a target="_blank" href="http://dygraphs.com/gallery/#g/highlighted-weekends">highlight specific periods of time</a> and <a target="_blank" href="http://dygraphs.com/gallery/#g/range-selector">select ranges of time</a>.</p>
<p>Chart.js allows you to create <strong>simple, aesthetically pleasing</strong> charts that pop into the page seamlessly on load.</p>
<p>Finally, Google Charts offered the <strong>most variety of out-of-the-box charts</strong>, compared to the other libraries. In addition to standard charts, Google Charts also supports <a target="_blank" href="https://developers.google.com/chart/interactive/docs/gallery/geochart">geographic maps</a>, <a target="_blank" href="https://developers.google.com/chart/interactive/docs/gallery/treemap">tree maps</a>, <a target="_blank" href="https://developers.google.com/chart/interactive/docs/gallery/sankey">sankey diagrams</a>, etc.</p>
<h3 id="heading-3-2-1-recap"><strong>3, 2, 1 … recap!</strong></h3>
<p>We’ve covered the many reasons <strong>why data visualization is powerful</strong>, the <strong>basic structure and steps</strong> to create a chart using a charting library, and a <strong>play-by-play comparison</strong> of 4 popular JavaScript libraries.</p>
<p>The most important step after you’ve selected a library and generated some visualizations is to <strong>communicate</strong>, and then <strong>iterate</strong>. Show your charts to others and ask them what they can and cannot interpret. Listen to their feedback and keep tweaking your charts. They’re teaching tools, and teaching tools should constantly evolve with the content and the viewers.</p>
<p>Thank you for reading!</p>
<ul>
<li>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</li>
</ul>
<p>Code for the charts I created are up on <a target="_blank" href="https://github.com/mandicai/boscc-charts">GitHub</a>.</p>
<p>Here are the <a target="_blank" href="https://www.slideshare.net/MandiCai/visualizing-your-data-in-javascript">presentation slides</a> that led to this article.</p>
<p>If you want to read about Bokeh and D3, check out <a target="_blank" href="https://medium.freecodecamp.org/charting-the-waters-between-bokeh-and-d3-73b3ee517478">Charting the waters: between Bokeh and D3</a>.</p>
<p>If you have any suggestions or feedback, drop a comment.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn to create a line chart using D3.js ]]>
                </title>
                <description>
                    <![CDATA[ By Sohaib Nehal Use the power of D3.js to draw beautiful representations of your data. Learn D3.js for free on Scrimba D3.js is an open source JavaScript library used to create beautiful data representations which we can view in any modern browser. ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-to-create-a-line-chart-using-d3-js-4f43f1ee716b/</link>
                <guid isPermaLink="false">66c359df4217dc7d72c63d1d</guid>
                
                    <category>
                        <![CDATA[ D3.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 02 May 2018 03:17:56 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*x-3p2C-nd9_RbXOZG0Dx0A.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sohaib Nehal</p>
<h4 id="heading-use-the-power-of-d3js-to-draw-beautiful-representations-of-your-data">Use the power of D3.js to draw beautiful representations of your data.</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/EUZuijdvOc8orJ9PUi3raR9Lm0LktF18luAT" alt="Image" width="800" height="448" loading="lazy">
<em>Learn D3.js for free on Scrimba</em></p>
<p>D3.js is an open source JavaScript library used to create beautiful data representations which we can view in any modern browser. Using D3.js, we can create various kinds of charts and graphs from our data.</p>
<p>In this tutorial, we are going to create a line chart displaying the Bitcoin Price Index from the past six months. We will be pulling in data from an external API and rendering a line chart with labels and an axis inside the DOM.</p>
<p><strong>We’ve also created a free D3.js course on Scrimba. <a target="_blank" href="https://scrimba.com/g/gd3js">Check it out here.</a></strong></p>
<h4 id="heading-getting-started">Getting started</h4>
<p>First of all, we will import the D3.js library directly from the CDN inside our HTML.</p>
<pre><code>&lt;html&gt;  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"index.css"</span>&gt;</span>  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>    <span class="hljs-tag">&lt;<span class="hljs-name">svg</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://d3js.org/d3.v4.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
</code></pre><p>We have also added an <code>&lt;svg&gt;</code> tag inside our HTML to create the line chart inside it using D3.js</p>
<p>Let’s now move towards writing our JavaScript code. First of all, we want to load our data of the Bitcoin Price Index from an external API once the DOM has been loaded.</p>
<h4 id="heading-fetch-data"><strong>Fetch Data</strong></h4>
<pre><code><span class="hljs-keyword">var</span> api = <span class="hljs-string">'https://api.coindesk.com/v1/bpi/historical/close.json?start=2017-12-31&amp;end=2018-04-01'</span>;
</code></pre><pre><code><span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">"DOMContentLoaded"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{   fetch(api)     .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">response</span>) </span>{ <span class="hljs-keyword">return</span> response.json(); })     .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>) </span>{          <span class="hljs-comment">//DO SOMETHING WITH DATA       })});</span>
</code></pre><p>In the code above, we are using the <code>fetch</code> method to get the data from an external API. We then parse it using the <code>.json()</code> method.</p>
<p>We now want to convert this data into key/value pairs so that they are in the format of <code>date:price</code>. For this, we are going to send our data to another function which will parse and return it in our desired form.</p>
<h4 id="heading-parse-data"><strong>Parse Data</strong></h4>
<pre><code>.....then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>) </span>{          <span class="hljs-keyword">var</span> parsedData = parseData(data) })
</code></pre><pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">parseData</span>(<span class="hljs-params">data</span>) </span>{   <span class="hljs-keyword">var</span> arr = [];   <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i <span class="hljs-keyword">in</span> data.bpi) {      arr.push(         {            <span class="hljs-attr">date</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(i), <span class="hljs-comment">//date            value: +data.bpi[i] //convert string to number         });   }   return arr;}</span>
</code></pre><p>We pass our data to a function <code>parseData</code> which returns another array of objects. Each object contains a date and the price of bitcoin on that particular date.</p>
<p>Once we have the data in our required format, we will send this data to the <code>drawChart</code> function in which all of the remaining code will be written using D3.js to render the line chart.</p>
<pre><code>.....then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>) </span>{    <span class="hljs-keyword">var</span> parsedData = parseData(data);   drawChart(parsedData);})
</code></pre><h4 id="heading-select-svg-element">Select SVG element</h4>
<p>In the <code>drawChart</code> function, we first of all select our SVG element and provide it with some styling.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">drawChart</span>(<span class="hljs-params">data</span>) </span>{
</code></pre><pre><code>   <span class="hljs-keyword">var</span> svgWidth = <span class="hljs-number">600</span>, svgHeight = <span class="hljs-number">400</span>;   <span class="hljs-keyword">var</span> margin = { <span class="hljs-attr">top</span>: <span class="hljs-number">20</span>, <span class="hljs-attr">right</span>: <span class="hljs-number">20</span>, <span class="hljs-attr">bottom</span>: <span class="hljs-number">30</span>, <span class="hljs-attr">left</span>: <span class="hljs-number">50</span> };   <span class="hljs-keyword">var</span> width = svgWidth - margin.left - margin.right;   <span class="hljs-keyword">var</span> height = svgHeight - margin.top - margin.bottom;
</code></pre><pre><code>   <span class="hljs-keyword">var</span> svg = d3.select(<span class="hljs-string">'svg'</span>)     .attr(<span class="hljs-string">"width"</span>, svgWidth)     .attr(<span class="hljs-string">"height"</span>, svgHeight);...
</code></pre><p>In the code above, we are setting the width and height of the SVG container by first selecting it using the <code>select()</code> method and then using the <code>attr()</code> method to assign the attributes.</p>
<p>We have also defined margins and are using their values in calculating the width and height attributes of the SVG container. These margin values will help us later in positioning and displaying our chart correctly.</p>
<p>Using CSS, we have given borders to our SVG container:</p>
<pre><code>&lt;style&gt;    .line-chart    {        <span class="hljs-attr">border</span>: <span class="hljs-number">1</span>px solid lightgray;    }&lt;/style&gt;
</code></pre><p>So far, we have nothing inside our DOM yet:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/amoiuppE703baUzbP-qvjHoeM8I0S4HgucSw" alt="Image" width="590" height="467" loading="lazy"></p>
<p>Next up, we are going to create a group element to hold our line chart, axis, and labels.</p>
<h4 id="heading-create-and-transform-group-element"><strong>Create and Transform Group Element</strong></h4>
<pre><code>...var g = svg.append(<span class="hljs-string">"g"</span>)   .attr(<span class="hljs-string">"transform"</span>,       <span class="hljs-string">"translate("</span> + margin.left + <span class="hljs-string">","</span> + margin.top + <span class="hljs-string">")"</span>   );
</code></pre><p>Grouping elements helps organize similar or related elements together. Here, after rendering a group element, we provide it some transformation.</p>
<p>D3 gives us various options to transform our elements. In the code above, we are using the <code>translate</code> property to reposition our group element with margins on its left and top.</p>
<h4 id="heading-add-scales"><strong>Add Scales</strong></h4>
<p>Now, we want to add scales to our chart.</p>
<pre><code><span class="hljs-keyword">var</span> x = d3.scaleTime().rangeRound([<span class="hljs-number">0</span>, width]);
</code></pre><pre><code><span class="hljs-keyword">var</span> y = d3.scaleLinear().rangeRound([height, <span class="hljs-number">0</span>]);
</code></pre><p>As we know, our data consists of dates and the value of Bitcoin on those dates. Therefore, we can assume that the x-axis would contain the dates and y-axis would contain values. That is how we can see the variation in the line chart with respect to time.</p>
<p>And so, in the code snippet above, we created a scale of type time on the x-axis and linear type on the y-axis. We are also providing these scales with the ranges as per the width and height of our SVG container.</p>
<h4 id="heading-create-a-line">Create a Line</h4>
<p>Let’s now move towards defining our line by using the <code>d3.line</code> method. We will be defining the x and y attributes of the line by passing in anonymous functions and returning the date object and bitcoin value for that particular day.</p>
<pre><code><span class="hljs-keyword">var</span> line = d3.line()   .x(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">d</span>) </span>{ <span class="hljs-keyword">return</span> x(d.date)})   .y(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">d</span>) </span>{ <span class="hljs-keyword">return</span> y(d.value)})   x.domain(d3.extent(data, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">d</span>) </span>{ <span class="hljs-keyword">return</span> d.date }));   y.domain(d3.extent(data, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">d</span>) </span>{ <span class="hljs-keyword">return</span> d.value }));
</code></pre><h4 id="heading-append-axises">Append Axises</h4>
<p>We are now going to append our left and bottom axes inside our group element for the line chart. The left axis will represent the value of bitcoin while the bottom axis displays the corresponding date.</p>
<pre><code>g.append(<span class="hljs-string">"g"</span>)   .attr(<span class="hljs-string">"transform"</span>, <span class="hljs-string">"translate(0,"</span> + height + <span class="hljs-string">")"</span>)   .call(d3.axisBottom(x))   .select(<span class="hljs-string">".domain"</span>)   .remove();
</code></pre><p>In the above code, we are appending a group element inside our main group and translating it at the very bottom our container. Then, we pass <code>d3.axisBottom</code> method in the call function where <code>d3.axisBottom</code> takes the parameter of <code>x</code> which is defined in the <strong>Add Scales</strong> section.</p>
<pre><code>g.append(<span class="hljs-string">"g"</span>)   .call(d3.axisLeft(y))   .append(<span class="hljs-string">"text"</span>)   .attr(<span class="hljs-string">"fill"</span>, <span class="hljs-string">"#000"</span>)   .attr(<span class="hljs-string">"transform"</span>, <span class="hljs-string">"rotate(-90)"</span>)   .attr(<span class="hljs-string">"y"</span>, <span class="hljs-number">6</span>)   .attr(<span class="hljs-string">"dy"</span>, <span class="hljs-string">"0.71em"</span>)   .attr(<span class="hljs-string">"text-anchor"</span>, <span class="hljs-string">"end"</span>)   .text(<span class="hljs-string">"Price ($)"</span>);
</code></pre><p>Similar to the bottom axis, we append another group element and then call on it the <code>d3.axisLeft</code> method which takes the parameter of <code>y</code>. Then, we also style our axis by assigning it different attributes and a label.</p>
<p>If we save and refresh the page, we can see our axes being rendered inside the DOM:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Os96ExJTGVVQuHqS-q3zqToG-pfBg5CztO6H" alt="Image" width="596" height="473" loading="lazy">
<em>Left and bottom axes</em></p>
<h4 id="heading-append-a-path">Append a Path</h4>
<p>In the last step, we will be appending a path inside our main group element. This path will actually draw the line chart as per the values of the data.</p>
<p>We pass our dataset using the <code>datum</code> method and then set the attributes of fill color, stroke color, and width. In the end, we set the attribute of <code>d</code> which actually gives instruction to the SVG path about where to connect the points of the path.</p>
<pre><code>g.append(<span class="hljs-string">"path"</span>).datum(data).attr(<span class="hljs-string">"fill"</span>, <span class="hljs-string">"none"</span>).attr(<span class="hljs-string">"stroke"</span>, <span class="hljs-string">"steelblue"</span>).attr(<span class="hljs-string">"stroke-linejoin"</span>, <span class="hljs-string">"round"</span>).attr(<span class="hljs-string">"stroke-linecap"</span>, <span class="hljs-string">"round"</span>).attr(<span class="hljs-string">"stroke-width"</span>, <span class="hljs-number">1.5</span>).attr(<span class="hljs-string">"d"</span>, line);
</code></pre><p>Here is the final result:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/I0yynRDidWlR6HOGbpdSs2aMS6cZJfUNysNt" alt="Image" width="598" height="464" loading="lazy">
<em>Line chart</em></p>
<h4 id="heading-conclusion">Conclusion</h4>
<p>Congratulations! We have successfully created the line chart using D3.js. You can check out the official documentation of <a target="_blank" href="https://github.com/d3/d3/wiki">D3.js</a> to learn more about different charts and graphs you can create.</p>
<p>If you’re interested in learning more about D3.js, be sure to <a target="_blank" href="https://scrimba.com/g/gd3js">check out our free course on Scrimba.</a></p>
<p>_I am Sohaib Nehal. I am a Full-Stack Web Application Developer. You can reach me at sohaib.nehal@ymail.com or on Twitter @Sohaib<em>Nehal. Thank you :-)</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn D3 in this free 10-part data visualization course ]]>
                </title>
                <description>
                    <![CDATA[ By Per Harald Borgen _Click here to get to the course._ D3.js is a JavaScript library which allows you to bring data to life using HTML, SVG, and CSS. Learning it will give you superpowers when it comes to extracting value from data, as you’ll basic... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-to-visualize-data-with-this-free-d3-js-course-2433b060f9dc/</link>
                <guid isPermaLink="false">66d85250afbaabf7a144af0f</guid>
                
                    <category>
                        <![CDATA[ D3.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 12 Apr 2018 19:41:06 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*rzZYWcWSMdmryHhB6Oq1ig.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Per Harald Borgen</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*sDp-GORp42nSv5xEuddOcw.png" alt="Image" width="800" height="463" loading="lazy">
_<a target="_blank" href="https://scrimba.com/g/gd3js?utm_source=freecodecamp.org&amp;utm_medium=referral&amp;utm_campaign=gd3js_launch_article">Click here to get to the course.</a>_</p>
<p>D3.js is a JavaScript library which allows you to bring data to life using HTML, SVG, and CSS. Learning it will give you superpowers when it comes to extracting value from data, as you’ll basically be able to create any visualization you can think of.</p>
<p>However, it’s not the easiest library to learn, so getting started can be a bit tricky. That’s why we’ve teamed up with web developer and instructor <a target="_blank" href="https://medium.com/u/4f68c487d7cf">Sohaib Nehal</a> and created a <a target="_blank" href="https://scrimba.com/g/gd3js?utm_source=freecodecamp.org&amp;utm_medium=referral&amp;utm_campaign=gd3js_launch_article">free full-length course on it.</a> Throughout the course, Sohaib will give you a soft introduction to the powerful library.</p>
<p>Let’s have a look at how it’s laid out!</p>
<h3 id="heading-the-content">The content</h3>
<p>The course consists of 10 screencasts which in total last less than an hour. It starts off with the most basic concepts, like selection, manipulation, data loading, and more. This lays the groundwork for the various visualizations you’ll learn to create throughout the rest of the course.</p>
<h4 id="heading-1-course-introduction">#1: Course introduction</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*QTASftirCvIEkkzu09ZNcw.png" alt="Image" width="800" height="401" loading="lazy"></p>
<p>As usual with Scrimba courses, it begins with a quick walk-through of the course content, along with an intro to D3.js and the instructor.</p>
<h4 id="heading-2-selection-and-manipulation">#2: Selection and Manipulation</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*H-7cY_zluQqHuYdvNMbFGw.png" alt="Image" width="800" height="309" loading="lazy"></p>
<p>The first thing you need to learn is how to select and manipulate DOM elements with D3.js. The library is actually pretty powerful in terms of manipulating the DOM, so you could theoretically use it as a <a target="_blank" href="https://blog.webkid.io/replacing-jquery-with-d3/">replacement for jQuery.</a></p>
<h4 id="heading-3-data-loading-and-binding">#3: Data Loading and Binding</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*5sEb4D4exhT8YZnpts-T9w.png" alt="Image" width="800" height="252" loading="lazy"></p>
<p>As you’re going to create visualizations, it’s important to learn how to load data in and also how to bind it to the DOM. So in this lecture, you’ll learn that.</p>
<h4 id="heading-4-creating-a-simple-bar-chart">#4: Creating a simple bar chart</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*Jm03LA1t_o3-GKjt84MLrA.png" alt="Image" width="800" height="424" loading="lazy"></p>
<p>In the third lecture, you’ll learn how to build your very first visualization: a simple bar chart. The reason we’re introducing you to building stuff so early on is that it’s much more fun to create visualizations than simply talking about theory. So we think you’ll enjoy this lesson.</p>
<h4 id="heading-5-creating-labels">#5: Creating labels</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*sDp-GORp42nSv5xEuddOcw.png" alt="Image" width="800" height="463" loading="lazy"></p>
<p>The next step is to add labels to the bar chart, as you often would want to do this in real life. This is a short and simple lecture. Here, I’d recommend you to play around with the positions of the labels, as that’s a simple and fun way of interacting with the code.</p>
<h4 id="heading-6-scales">#6: Scales</h4>
<p>Scales are a critical concept in D3. They allow you to map your data to other relevant ranges, for example, the amount of space you have available. So in this lecture, you’ll learn about the <code>scaleLinear()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> yScale = d3.scaleLinear()  
    .domain(\[<span class="hljs-number">0</span>, d3.max(dataset)\])  
    .range(\[<span class="hljs-number">0</span>, svgHeight\]);
</code></pre>
<h4 id="heading-7-axes">#7: Axes</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*nag8GxIZpnUrvtfM9HaYNg.png" alt="Image" width="800" height="426" loading="lazy"></p>
<p>Axes are an integral part of any chart, and D3 provides you with a few simple methods for creating them. This lesson builds upon the last one, as it takes advantage of scales when creating the axes. It also sets you up for understanding the super-cool line chart you’ll learn in the final screencast of the course.</p>
<h4 id="heading-8-creating-svg-elements">#8: Creating SVG elements</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*FZdi_TA96EMc0B8I-Tt6Cg.png" alt="Image" width="800" height="431" loading="lazy"></p>
<p>Even though you’ve already created SVG elements previously in the course, it’s such an important concept that it deserves its own lecture. In it, you’ll learn about the <code>&lt;rect&gt;</code>, <code>&lt;circle&gt;</code> , and <code>&lt;line&gt;</code> elements.</p>
<h4 id="heading-9-creating-a-pie-chart">#9: Creating a pie chart</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*JvNCACLTK_o7Q1D2AlMVuw.png" alt="Image" width="800" height="419" loading="lazy"></p>
<p>Pie charts are handy in many cases, so in this lecture, you’ll learn how to create one. D3 provides a simple API for doing this, so it shouldn’t be difficult for you at this point.</p>
<h4 id="heading-10-creating-a-line-chart">#10: Creating a line chart</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*NSDd3qCL8-xYDsTnOMQ5KA.png" alt="Image" width="800" height="430" loading="lazy"></p>
<p>Finally, you’ll learn how to create a line chart to visualize the Bitcoin price. To get the data, you’ll use an external API. This project will also tie together a lot of the concepts you’ve learned throughout the course, so it’s a great visualization to end with.</p>
<p>And that’s it! After going through these ten lessons, you should be well set up for starting to use D3.js in your job or for personal projects.</p>
<p>If you reach this point, we’d really appreciate if you’d give <a target="_blank" href="https://medium.com/u/4f68c487d7cf">Sohaib</a> a shout-out on <a target="_blank" href="https://twitter.com/Sohaib_Nehal">Twitter</a>!</p>
<h3 id="heading-the-scrimba-format">The Scrimba format</h3>
<p>Before you leave, let’s also have a quick look at the technology behind the course. It’s built using <a target="_blank" href="http://scrimba.com">Scrimba</a>, an interactive coding screencast tool. A “scrim” looks like normal video, however, it’s fully interactive. This means that you can edit the code inside the screencast.</p>
<p>Here’s a gif which explains the concept:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*4PWxbgV--7ZHlB-YVqavJg.gif" alt="Pause the screencast → Edit the code → Run it! → See your changes" width="1200" height="571" loading="lazy"></p>
<p>Pause the screencast → Edit the code → Run it! → See your changes</p>
<p>This is great for when you feel you need to experiment with the code in order to properly understand it, or when you simply want to copy a piece of the code.</p>
<p>So what are you waiting for? <a target="_blank" href="https://scrimba.com/g/gd3js?utm_source=freecodecamp.org&amp;utm_medium=referral&amp;utm_campaign=gd3js_launch_article">Head over to Scrimba and take the free course today!</a></p>
<hr>
<p>Thanks for reading! My name is Per Borgen, I'm the co-founder of <a target="_blank" href="https://scrimba.com">Scrimba</a> – the easiest way to learn to code. You should check out our <a target="_blank" href="https://scrimba.com/g/gresponsive?utm_source=freecodecamp.org&amp;utm_medium=referral&amp;utm_campaign=gd3js_launch_article">responsive web design bootcamp</a> if want to learn to build modern website on a professional level.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/bootcamp-banner.png" alt="Image" width="600" height="400" loading="lazy">
_<a target="_blank" href="https://scrimba.com/g/gresponsive?utm_source=freecodecamp.org&amp;utm_medium=referral&amp;utm_campaign=gd3js_launch_article">Click here to get to the advanced bootcamp.</a>_</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
