Is there a method to extract the y value for a specific x value that is not part of the current data set in a Chart.js graph

I have a set of data points like

{ x: 5, y: 10 }, { x: 10, y: 15 }, { x: 20, y: 25 }
. With Chart.js, I can easily create a chart based on these points. Is there a method to retrieve the y value for a specific x value, such as 13, from the rendered chart? My current setup involves Chart.js version 2.9.3 and vue.js. Any suggestions or guidance would be greatly appreciated!

Answer №1

To accomplish this task, you can utilize the function provided below:

function calculateValueAt(x) {
  let xScale = graph.scales['x-axis-0'];
  let yScale = graph.scales['y-axis-0'];
  let dataValues = graph.data.datasets[0].data;
  let position = dataValues.findIndex(obj => obj.x >= x);
  let previous = dataValues[position - 1];
  let nextPoint = dataValues[position];
  if (previous && nextPoint) {
    let slopeValue = (nextPoint.y - previous.y) / (nextPoint.x - previous.x);
    return previous.y + (x - previous.x) * slopeValue;
  }
}

The majority of the code has been borrowed from interpolate.js, an impressive library known as chartjs-plugin-crosshair.

Please refer to the runnable code snippet below to witness its functionality:

const graph = new Chart("graph", {
  type: 'line',
  data: {
    datasets: [{
      label: '',
      data: [{ x: 5, y: 10 }, { x: 10, y: 15 }, { x: 20, y: 25 }],
      type: 'line',
      borderColor: 'red',
      fill: false,
    }],
  },
  options: {
    responsive: false,
    scales: {
      xAxes: [{
        type: 'linear'
      }]
    }
  }
});

function calculateValueAt(x) {
  let xScale = graph.scales['x-axis-0'];
  let yScale = graph.scales['y-axis-0'];
  let dataValues = graph.data.datasets[0].data;
  let position = dataValues.findIndex(obj => obj.x >= x);
  let previous = dataValues[position - 1];
  let nextPoint = dataValues[position];
  if (previous && nextPoint) {
    let slopeValue = (nextPoint.y - previous.y) / (nextPoint.x - previous.x);
    return previous.y + (x - previous.x) * slopeValue;
  }
}

let xValue = 13;
let yValue = calculateValueAt(xValue);
console.log('x-coordinate: ' + xValue + ' -> y-coordinate: ' + yValue);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="graph" height="200"></canvas>

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

What steps do I need to take in order to implement a functional pagination menu in Vue?

I downloaded and installed laravel-vue-pagination with the following command: npm install laravel-vue-pagination After that, I globally registered it in my app.js file: Vue.component('pagination', require('laravel-vue-pagination')); F ...

JavaScript's Use of Brackets

I’ve been working on a new project that involves adding links. To do this, users can input both the link URL and the text they want displayed. I used a prompt to gather this information. Here’s the code snippet I wrote: document.getElementById(ev.targ ...

Is there a way to dynamically import a JSON file within an ECMAScript module?

Currently, I am attempting the following in my code: let filePath = '../../data/my-file.json' import inputArray from filePath assert { type: 'json' } The outcome of this operation is as follows: file:///.../script.mjs:5 import inputArr ...

Removing a selected row from a data table using an HTTP request in Angular 2

I am working with a table that has data retrieved from the server. I need to delete a row by selecting the checkboxes and then clicking the delete button to remove it. Here is the code snippet: ...

Simulating a service call in an AngularJS controller

Here is the code for my Controller: (function () { 'use strict'; angular.module('myApp').controller('myCtrl', function ($scope, myService) { // Start -----> Service call: Get Initial Data myService ...

Remove the active class from a list item using History.js

My goal is to add the active class to a link when clicked in my AJAX app, triggering statechange on History.js. I'm struggling with saving the current active link(s) with the state so that the active class is appropriately added or removed when naviga ...

Issue with redirect using Node.js promise

I’ve created a settings page where users can add and remove filters. To handle the deletion process, I’ve implemented this jQuery function: $('#delete-filter').click(function (e) { var filtername = $('#filter-list').val(); ...

The Safari browser is currently having trouble loading the data sent back from the server

After successfully developing and deploying my website carspeedyrental.com, I received reports from some clients indicating that the website does not display available cars on the iPhone Safari browser. Interestingly, when tested on various browsers on A ...

Replicate the anchor's functionality (opening in a new window when 'ctl' is pressed) when submitting a form

I have a question that may seem unconventional - Is there a graceful method to replicate the functionality of an anchor tag when submitting a form? I want users to be able to hold down the control key while submitting a form and have the result open in a ...

When I click a button in d3 to refresh the data on my bar graph, the text fails to update accordingly

I've successfully created a series of data lists that modify the bargraph. Unfortunately, due to their differing x and y values, they end up printing new values on top of existing ones. Shown below is an image illustrating the issue where x and y val ...

Having trouble with dragging a file from one box to another in HTML5. The functionality is not working

Encountering an issue where the image does not display in the left box after dropping it. Here is the sequence of events: Before dragging the image: After dragging the image, it fails to display: The error reported on Chrome is as follows: GET file:/// ...

Tribal Code Typescript Compiler

Typescript is a great alternative to Javascript in my opinion, but it bothers me that it requires node.js as a dependency. Additionally, I find it frustrating that there seems to be only one compiler available for this language, and it's self-hosted. ...

Remove a row from a table using the hyperlink reference

I am facing an issue where I want to delete a row in the table along with the corresponding database entry by clicking on a href link, but it doesn't work as expected: <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"& ...

Switching images using jQuery

Issue I'm feeling overwhelmed by the abundance of JavaScript code hints and finding it difficult to determine where to begin. Any assistance would be greatly appreciated. Essentially, I have a primary full-screen background image set in the CSS on t ...

What is the best way to set up localStorage with a multi-dimensional array

I am struggling with modifying my local storage and it's taking up a lot of my time. Initially, I set it up like this: localStorage.setItem('example','{"data": []}'); It was working fine, but now I need to structure it like the ...

Using Angular JS to connect Promises while preserving data

There have been discussions about chaining promises, but this scenario presents a unique challenge. I am currently working on making multiple http get requests in my code. The initial call returns an array, and for each object in this array, another http c ...

ways to make a list element inaccessible by using either Javascript or jQuery

When the user clicks on my eraser, I want the color to be hidden or not display its dropdown elements. I attempted this with the following code snippet. $('#chooseEraser').mousedown(function(e){ curTool = "eraser"; checkEraser ...

Utilizing Node.js and Mongoose, effortlessly update data in Mongo DB regardless of the existence of the collection

How can I update a field that may or may not exist? I attempted the following code: db.foo.update( { site: '"wisdom'}, { $set: {'club': 'fc barcelona'}}, (upsert=true) ) ...

Exporting all components using require: A complete guide

Currently, I am working on a Vue js application where I am tasked with exporting all the files and components from a specific directory. These files/components need to be imported into a separate file named paths.js. If I use the require function to impor ...

Extract latitude and longitude data using Mapbox's autocomplete feature

Currently, I have integrated Mapbox with autocomplete in a Vue component: <template> <div> <div id='geocoder'></div> </div> </template> <script> import mapboxgl from 'mapbox-gl& ...