Create a line graph overlaying an area chart

I am currently working on developing a chart using D3js v5.12.0.

So far, I have successfully created an area chart with the year variable on the X-axis and the earth_footprint variable on the Y-axis.

You can find the data for this chart at the following link: https://raw.githubusercontent.com/cvrnogueira/CODWorkData/master/database/final_data_set.json

Now, my goal is to add a line chart on top of the existing area chart. This new line chart should have the year variable on the X-axis and pop_total on the Y-axis. pop_total is another variable included in the dataset.

Despite looking at tutorials that demonstrate how to draw a line on a bar chart, I've been struggling to adapt these techniques to my code which is based on an area chart.

CSS

#area-chart {
  text-align: center;
  margin-top: 40px;
}

.selection {
  fill: none;
}

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div id="area-chart"></div>
</body>
</html>

JS


var url = "http://raw.githubusercontent.com/cvrnogueira/CODWorkData/master/database/final_data_set.json";


  d3.json(url)
      .then(function(data) {
      
      data =  data.filter(dataPoint => dataPoint.country_code == 'BRA');
      data =  data.filter(element =>  element.hasOwnProperty("earth_footprint"));

const heightValue =

... more unique content ...
 

Answer №1

To display that line, you will need a line generator:

const line = d3.area()
    .x(dataPoint => xScale(dataPoint.year))
    .y(dataPoint => yScale(dataPoint.pop_total));

However, the yScale is based on the maximum value of earth_footprint, causing the values of pop_total to be far out of scale. Therefore, you must create another scale for the line generator:

const yScale2 = d3.scaleLinear()
    .range([height, 0])
    .domain([0, d3.max(data, dataPoint => dataPoint.pop_total)]);

After setting up the scales, append the path as follows:

grp.append("path")
    .attr("d", line);

The issue now is dealing with two visual representations (area and line) using different scales. You will need an additional axis for the line. That task is left for you.

Here is the revised code:

// Code example displayed here
// JavaScript, SVG elements, D3.js library, and more...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain the location information upon the loading of the webpage

I am currently in the process of developing a website using HTML, CSS, and JavaScript. My goal is to automatically retrieve the user's location when the page loads, without requiring them to click a button. I would greatly appreciate any assistance wi ...

Tab knockout binding

I have a section in my HTML with 2 tabs. The default tab is working properly, but when I attempt to switch to the other tab, I encounter an error. Can anyone provide assistance in determining why this error occurs? Here is the HTML code: <ul class="na ...

Preload-webpack-plugin does not support pre-fetching files

I have a query about prefetching and preloading content. In my vue app, I noticed that after building, I have duplicate files loaded in my dist/index.html file. Here is an example: Additionally, the "scripts" are not being preloaded/prefetched as expec ...

The response from Ajax is being duplicated with each click

Upon clicking the "Add More" button, I dynamically display two dropdowns. The first dropdown is displayed instantly, while the second dropdown requires an Ajax call to fetch and display its content. The functionality of displaying the second dropdown also ...

What is the best way to center a progress bar vertically using Twitter Bootstrap?

I'm currently utilizing the progress bar feature in twitter-bootstrap. My goal is to align it vertically to match the appearance in the following image: While I came across this discussion thread, it seems to be outdated. As a workaround, I have im ...

Top option for managing an excess of pins on Google Maps

Let me walk you through my Google Maps setup process: To start, I retrieve the locations of all markers (usually under 300) from a database and send them to JavaScript in JSON format. Within JavaScript, I parse the JSON data, iterate through the marker a ...

Is it possible to close a MongoDB connection using a different method other than the one mentioned in this function?

I am facing a challenge with uploading a substantial data set from my node.js application to a mongodb. The process involves running a for loop to fetch each result. Initially, I established the connection to the MongoDB within every iteration of the loop, ...

Interactive website that transitions to a fresh page as we scroll further

As a beginner in web design, I've noticed a trend of companies using websites that automatically transition to the next page when scrolling down. An example of this is . What is this type of template called and are there any open source designs availa ...

Retrieving precise passed arguments in the $(document).ready function

I am working on a gridview where I need the rows to expand and display the BatchID that is passed. Currently, I am using href="javascript:switchViews('div<%# Eval("BatchID")%>', 'one');" to pass this information, but I'm stru ...

Error encountered when trying to access Proxy Object or Object[] in MobX with TypeScript

In my MobX Store, I have a straightforward structure: import { observable, action, makeObservable } from "mobx" import { BoxShadow, ShadowValues } from "./types" import { boxShadow } from "./constants" interface IStore { ...

Exploring the Mystery of why Three.js Fails to Apply Textures to Objects

I'm attempting to add a texture to an object with the following code: <html> <head> <title>My first Three.js app</title> <style> body { margin: 0; } canvas { width: 100%; h ...

Position the Bootstrap 5 navbar at the top of the page and set it

Is there a way to use the fixed-top class on a navbar without making it full width and overlapping the container? This is the code: <div class="container" style="border: 1px solid;"> <nav class="navbar fixed-top n ...

The input field is not functioning properly within the vue-drag-resize component

I have incorporated vue-drag-resize from https://github.com/kirillmurashov/vue-drag-resize in my project. Unfortunately, I am facing an issue where I am unable to focus and type anything inside an input text field that is contained within the vue-drag-res ...

What are some cookie serialization techniques in JavaScript and PHP?

I have a form with multiple select options that I want to save in a cookie for user convenience. The goal is to make the serialization of the cookie easily readable in both JavaScript and PHP, allowing me to set the form onLoad and filter search results ba ...

Using JQuery, you can toggle a newly created DIV element by linking it to `$(this)` instead of `$(this).closest()`

In the comment section, there is a link called "Reply" that triggers a pop-up comment box when clicked. However, I want the comment box to disappear if the "reply" button is clicked again, as it currently keeps opening more comment boxes. $('.replyli ...

How to send a JSON object using Node.js Express 4.0

I'm currently working on parsing the JSON object sent in the request and displaying the data being transmitted. Below is my post request: $.ajax({ url: url, type: 'POST', contentType: 'application/json' ...

Searching for a way to display just a portion of a rendered HTML page using JavaScript

With the JavaScript code window.print(), it is possible to print the current HTML page. If there is a div in an HTML page (such as a page generated from an ASP.NET MVC view), the aim may be to only print that specific div. Is there any jQuery unobtrusive ...

Displaying FontIcon in a NativeScript alert box

Would it be possible to display a fonticon on a Nativescript dialog? Similar to this example? dialogs.alert({ title: // set icon as text message: "Check-in Successful" }).then(()=> { console.log("Dialog closed!"); }); Is it feasible to ...

Attempting to employ $set in conjunction with stringify, unfortunately without success

I am currently trying to utilize this function to edit a specific space in my MongoDB database. However, being new to this, I am struggling to understand what is going wrong. The error message "missing ) after argument list" keeps appearing. Any help and ...

React Native: Picker value remains static

I'm encountering an issue where the value of the picker does not change when I select a new value from it. This problem started occurring after I added the onValueChange function. If anyone has any insights or suggestions on how to resolve this, I wou ...