Need assistance with filling the space between two vertical lines on a chart using the chartjs library?

Can someone help me figure out how to fill the area between two line graphs using chartjs? I know how to do it when one line is on top of the other, but I'm struggling with getting the area between two lines that are side by side.

For example, I'd like to achieve something similar to this graph:

Here's the code snippet I've been working with:

    const ctx = document.getElementById('myChart');
    const myChart = new Chart(ctx, {
        type: 'scatter',
        data: {
          datasets: [{
            label: 'line 1',            
            data:[
              {x: -11, y: 7},
              {x: -11, y: 7},
              {x: -1, y: 8},
            ],
            showLine: true,
            borderColor: '#009999',
            backgroundColor: '#009999',
          }, 
          {
            label: 'line 2',
            data: [
              {x: 0, y: 7},
              {x: 0, y: 7},
              {x: 8, y: 8},
            ],
            showLine: true,
            borderColor: '#f00',
            backgroundColor: '#f00',
          }
        ]
        },
        options: {
          responsive: false,
        }
    });

Answer №1

If you're looking to achieve this, I recommend using a dedicated plugin.

Here's an example of a plugin I've developed (which can be further improved):

const customPlugin = {
  id: 'myfill',
  beforeDatasetsDraw(chart, args, options) {
    const {ctx, data} = chart;
    ctx.save();
    ctx.fillStyle  = 'rgba(47, 98, 156, 0.2)';
    ctx.beginPath();
    let meta = chart.getDatasetMeta(0);
    let e = meta.data[0];
    ctx.moveTo(e.x, e.y);
    e = meta.data[1];
    ctx.lineTo(e.x, e.y);
    meta = chart.getDatasetMeta(1);
    e = meta.data[1];
    ctx.lineTo(e.x, e.y);
    e = meta.data[0];
    ctx.lineTo(e.x, e.y);
    ctx.fill();
    ctx.restore();
  }
};
const canvas = document.getElementById('myChart');
const myCustomChart = new Chart(canvas, {
   type: 'scatter',
   plugins: [customPlugin],
   data: {
     datasets: [{
            label: 'line 1',            
            data:[
              {x: -11, y: 7},
              {x: -1, y: 8},
            ],
            showLine: true,
            borderColor: 'rgb(47, 98, 156)',
          }, 
          {
            label: 'line 2',
            data: [
              {x: 0, y: 7},
              {x: 8, y: 8},
            ],
            showLine: true,
            borderColor: 'rgb(47, 98, 156)',
          }
        ]
        },
        options: {
          responsive: false,
        }
    });
.customChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e0d060f1c1a40041d2e5d4057405f">[email protected]</a>/dist/chart.min.js"></script>
<html>
  <body>
    <div class="customChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

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

Utilizing a window.onload function in Microsoft Edge

After trying to run some code post-loading and rendering on the target page, I was recommended to use the Window.load function. This method worked flawlessly in Firefox and Chrome, but unfortunately, I couldn't get it to function in IE. Is there an al ...

Tips for positioning a picklist field dropdown on top of a lightning card in Lightning Web Components

Attempting to resolve an issue with CSS, I have tried adding the following code: .table-responsive, .dataTables_scrollBody { overflow: visible !important; } However, the solution did not work as expected. Interestingly, when applying a dropdown pickli ...

The problem I am facing is with the React Ant d Modal Component, where I am unable to render the

Hey there! I'm currently working with React Js and the 'Ant design Modal Component'. When I click on a button, the modal should open and display the content of each user with their unique ID. However, I'm facing an issue where all modal ...

What is the best way to toggle the navigation bar between opened and closed

I'm having trouble with this navbar not opening and closing properly. Can anyone suggest what script I should add? <nav class="navbar navbar-expand-md"> <a class="navbar-brand" href="/"> <img src=&qu ...

Guide on parsing a JSON array passed from JavaScript using json_decode?

I am attempting to send JSON string encoded data to the PHP backend. In order to achieve this, I am utilizing a GET parameter with URL encoded JSON data in the form of an array similar to this: ["mystring1","mystring2"] However, when I try to decode it us ...

Customize the MUI Slider Component with unique colored thumbs

Check out MUI's slider component at this link. I'm using it to let users select a value range with two thumbs. You can find the documentation for MUI's multi-thumb slider here. If you want to customize the style of the slider thumb, visit ...

Exploring the process of using querySelector() to locate specific class and div IDs in JavaScript code

My objective is to make the id="myDropdownTop" trigger the corresponding drop-down menu. The problem lies in my script code, particularly the final line: ("div.dropdown-content").classList.toggle("show"); does not seem to be functioning correctly. <!D ...

send Javascript syntax errors and console.log output to a different location

I'm experimenting with ways to redirect output from the javascript console to my own custom functions. Here's what I've attempted: window.console.error = window.console.debug = window.console.log window.console.log = mylog; function mylo ...

"Fixing the Vertical Order of Divs with Jquery: A Step-by-

Before I completely lose my mind, I need some help with a coding issue. Right now, I have two initial divs displayed. The user should be able to add these divs below the original ones as many times as they want, or remove them if needed. I've been att ...

Location of Custom HTML Widget in Django-Dashing

I've encountered a dilemma while using the Django-Dashing framework, specifically regarding the placement of my HTML file for a custom widget. I have meticulously configured the code in my dashboard.html file to ensure proper loading. {% extends &apo ...

Ascending and descending functions compared to Ext.getCmp()

I'm feeling a bit lost trying to figure out which method to use when using grep object - should I go with up(), down(), or Ext.getCmp(ID)? Personally, I find it simpler to assign an ID to the object and then retrieve it using Ext.getCmp('ID&apos ...

Printing with Scalable Vector Graphics (SVG) Technology

I have a unique challenge with an SVG file of a flat displayed in my browser - I need to print it out at a specific scale. I've been using SVG.js to manipulate the content, but I'm struggling to find the right combination of viewport and viewbox ...

Using jquery to remove textbox value when checkbox is unchecked

I have a single datatable created using jQuery. The first column of the table consists of checkboxes, and the last column contains textboxes. Because these elements are generated dynamically, they end up having identical IDs and names as shown below: $ ...

The Chrome browser does not recognize Sys.WebForms

I am encountering an issue with my Web-Application when trying to perform partial updates. The error message "Sys.WebForms is undefined in Chrome (latest version)" keeps popping up. Despite my extensive research efforts, I have not been able to find a solu ...

Convert a JSON weather report to a JavaScript timestamp for time conversion

When retrieving weather data from forecast.io in JSON format, there is a timestamp included: time:1445767494,"summary":"صافِ","icon":"clear-day","precipIntensity":0,"precipProbability":0,"temperature":32.99,"apparentTemperature":31.41,"dewPoint":10.5 ...

Issue with AngularJS: Copying and appending with $compile is not functioning properly

Below is the snippet of my angularjs Controller var $tr = angular.element("#parent" + obj.field_id).find("tbody"), $nlast = $tr.find("tr:last"), $clone = angular.copy($nlast); $clone.find(':text').val('' ...

In my programming world, 'i' is a mysterious being - always undefined, except when it decides

Currently, I am utilizing Vue, Vuedraggable, and Vuetify in my project. I have encountered an issue where I am unable to use 'let' to define the index for my loop as it always returns undefined. Strangely, using 'var' instead of ' ...

An alternative to passing AngularJS expressions to PHP or Ajax

Within my PHP/HTML file, I have an AngularJS expression that looks like this: {{data.po_id}} This expression is included as <td>{{data.po_id}}</td> within a table row. I am trying to use this expression as a parameter for a PHP function in t ...

Employ jquery to exclusively add either a beginning tag or closing tag

As I continue to learn, I have discovered that using replaceWith('<section>') or after('<section>') results in the full element being inserted in both scenarios: <section></section> Interestingly, when at ...

Choose elements in jQuery that lack a specific class

How can I efficiently select all elements with the .hi class that do not include the .image class? <div class="hi"> <div class="hue"> <div class="image"> 456 </div> </div> </d ...