Using dates as the X axis in Chart.js can be achieved even when there is no corresponding Y axis value

My goal is to ensure that the chart always displays a value on the final X axis,

I am unable to use "distribution: 'series'" as it causes the chart to go out of scale,

Guessing the correct value to set for "time: {min / max}" in order to exceed the last value is a challenge, and I also cannot manually determine the data to be displayed on the Y axis.

Is there a way to define data as shown in the following example?

X axis values:

1 - 2020-04-01
2 - 2020-04-03
3 - 2020-04-08
4 - 2020-04-10
5 - 2020-04-15

With the Y axis like this:

x   x           x  x       x
|_____________|____________|__
04-01       04-07         04-15

Currently, I have manually defined the values on the axis as 04-01 / 04-07 / 04-15, even though none of the data corresponds to the date 04-07.

https://i.sstatic.net/M1WwV.jpg

Answer №1

It is evident from your code that you have experimented with various methods, such as ticks.autoskip and ticks.maxTicksLimit. While both of these options limit the number of tick labels when necessary, they do not guarantee that the last label corresponds to the last data point.

To address this issue in a more organized manner, you need to implement your custom ticks.maxTicksLimit on the xAxis. Here's how you can achieve this:

  1. Create a labels array based on the timestamps in your data. This array should include the start and end times of the data, along with the specified number of evenly distributed times in between (refer to the function createLabels in the modified code below).
  2. Instruct Chart.js to generate ticks on the xAxis using the provided labels by setting tick.sources: 'labels'.

**Modified JavaScript Code:**

const data = [
  { t: new Date("2015-3-15 13:30"), y: 12 },
  { t: new Date("2015-3-25 13:20"), y: 21 },
  ... // Additional data points
];

function createLabels(maxTicksLimit) {
  const times = data.map(o => o.t.getTime());
  const startTime = times[0];
  const endTime = times[times.length - 1];
  const tickGap = (endTime - startTime) / (maxTicksLimit - 1);
  const labels = [startTime];
  
  for (let i = 1; i < maxTicksLimit - 1; i++) {
    labels.push(startTime + i * tickGap);
  }
  labels.push(endTime);
  return labels;
}

var myChart = new Chart(document.getElementById("examChart"), {
  type: 'line',
  ... // Chart configuration details
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<div class="container" style="width: 50%;">
  <canvas id="examChart"></canvas>
</div>

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

Generating data within an express route (with the use of socket.io-client)

Recently, I made the decision to refactor my code in order to separate the front and back end, which were previously combined into one service. However, I am now facing an issue where I need the web server to emit data to the data server after validation. ...

Build desktop-style applications using a unique user interface library and integrated development environment designed specifically for HTML, JavaScript

I am looking to create a desktop application using HTML, JavaScript, and AJAX for the purpose of making it available on multiple platforms. I was wondering if there is a UI library and web IDE similar to WebOS Enyo that I can use to build my HTML/AJAX app? ...

Sending a piece of state information to a different component

Hey, I'm a new React developer and I'm struggling with a particular issue. I've included only the relevant code snippets from my app. Basically, I want to retrieve the data from the clicked Datagrid row, send it to a Dialog form, and then p ...

Running jQuery scripts through PHP

$("#bt-potrdi").click( function(e) { e.stopPropagation(); $("#belina").css({"z-index":200}); $("body").addClass("ext"); $("#vpisok_frame").css({"z-index":250}).fadeIn(200); }); Upon clicking the button, the ...

An error occurred while trying to serialize the `.res` response received from the `getServerSideProps` function in

I encountered the following issue while utilizing the getServerSideProps function to fetch data from Binance API. import binance from "../config/binance-config"; export async function getServerSideProps() { const res = await binance.balance(( ...

Preventing ReactJS tooltips from exceeding the boundaries of the screen

Here is a simple demo showcasing blocks with tooltips that appear when hovered over. However, there seems to be an issue with the functionality. The tooltip should ideally be displayed either from the left or right side of the block. To determine the size ...

Change the input field to uppercase using JavaScript but do not use inline JavaScript

Hey there! I have a basic script set up (see below) with an input field allowing users to enter a query. This query is then sent to a socrata webservice to request specific data, which is displayed in an alert box. So far, everything works smoothly. var l ...

I am trying to figure out how to dynamically set the deployUrl during runtime in Angular

When working with Angular, the definition of "webpack_public_path" or "webpack_require.p" for a project can be done in multiple ways: By setting the deployUrl in the .angular-cli.json file By adding --deployUrl "some/path" to the "ng build" command line ...

AngularJS - ng-change does not trigger for checkbox that toggles the class "switch"

CSS Styling: <span style="color: blue;">Hello, World!</span> JavaScript Function: function showMessage(){ alert('Hello!'); } I tried to implement a span element with blue text color. However, the function that was supposed to ...

Creating a custom toJSON function for a property declared using Object.defineProperty

Let's consider a scenario where we have an object with a specific property that is meant to reference another object, as shown below: Object.defineProperty(parent, 'child', { enumerable: true, get: function() { return this._actualCh ...

What is the best way to conceal the header on a 404 error page?

<HeaderContainer> <Switch> <Route exact path='/counters' component={ParentCounterContainer}/> <Route exact path='/about' component={AboutContainer} /> <Route exact path='/' component={H ...

Using HTML div tags to create a looping expression that can interact with Javascript

Currently, I am working on a Ruby on Rails project and I am facing a challenge with looping variables in an HTML form to reduce the amount of manual code I have to write. However, when I attempt to evaluate an expression in the id attribute, the JavaScript ...

How to manage multiple items within a single MUI/React TextField

Recently diving into the world of JS, React, and MUI, I find myself faced with a challenge involving a MUI TextField that is supposed to handle multiple values. For example: 1*10 5*50 13*250 5*50 1*10 3*33.33 4*25 3*33.33 All on a single line. These ...

"Eliminate the headers of columns within the collapsible rows on the ui-grid interface

I am working with an expandable table and trying to figure out how to hide the column headers for only the expandable rows within the table. I experimented with including showHeader : false in the subGridOptions, but without success as the headers are stil ...

Utilizing the $.ajax method along with the onreadystatechange event

Is there a way to use the onreadystatechange event of the underlying XMLHttpRequest in JQuery's (version 2.0.2) $.ajax(...) function to trigger synchronous ajax requests for displaying accurate status indications during long-running processes? It seem ...

Obtain data from an external XML source using jQuery

Hey there! I'm looking to scrape/parse some information from an external XML file hosted on a different domain and display it on my website. I attempted the following but unfortunately, it didn't work as expected: jQuery(document).ready(functio ...

In Javascript, navigate to a specific section by scrolling down

Currently, I am in the process of enhancing my portfolio website. My goal is to incorporate a CSS class once the user scrolls to a specific section on the page. (I plan to achieve this using a JavaScript event). One approach I am considering is initially ...

"Selecting an element through Drag/Drop will result in the element being

INQUIRY I've encountered an issue with a draggable element ($("#draggable")) that interacts with a checkbox ($('#checkable')). When the $('#draggable') is dragged onto a box ($('#droppable')), it checks $(&apos ...

Exploring the power of Angular JS promises through ng-repeat

My current project involves fetching latitude and longitude coordinates from a postcode using an API, then utilizing those coordinates to retrieve data on street level crimes near that location on a specific date through the UK police API. However, I have ...

Maintain the tab order for elements even when they are hidden

Check out this demonstration: http://jsfiddle.net/gLq2b/ <input value="0" /> <input id="test" value="1" /> <input value="2" /> By pressing the TAB key, it will cycle through the inputs in order. If an input is hidden when focused, press ...