Animating Chart.js 2 from right to left instead of from top to bottom

Here is the issue demonstrated in the jsfiddle below.

Initially, the data inserts work well. However, when the data set reaches a cap of 10, an unwanted behavior occurs where the data points are animated top-down instead of moving leftward. This can be quite distracting.

Check it out here.

setInterval(function () {
 data.labels.push(Math.floor(Date.now() / 1000));
 data.datasets[0].data.push(Math.floor(10 + Math.random() * 80));

 // limit to 10
 data.labels = data.labels.splice(-10);
 data.datasets[0].data = data.datasets[0].data.splice(-10);

 chart.update(); // addData/removeData replaced with update in v2
}, 1000);

Is there a way to make the line chart move left so that newly inserted data points appear on the right, rather than experiencing the distracting up-and-down animation?

Thank you.

Answer №1

This specific code implementation utilizes the streaming plugin effectively to achieve the desired outcome.

To view this code in action, visit: http://jsfiddle.net/nagix/kvu0r6j2/

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4d7dcd5c6c0dec799c4d8c1d3ddda99c7c0c6d1d5d9dddad3f4859a819a84">[email protected]</a>/dist/chartjs-plugin-streaming.min.js"></script>
var ctx = document.getElementById("chart").getContext("2d");
var chart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [],
        datasets: [{
            label: "My First dataset",
            backgroundColor: "rgba(95,186,88,0.7)",
            borderColor: "rgba(95,186,88,1)",
            pointBackgroundColor: "rgba(0,0,0,0)",
            pointBorderColor: "rgba(0,0,0,0)",
            pointHoverBackgroundColor: "rgba(95,186,88,1)",
            pointHoverBorderColor: "rgba(95,186,88,1)",
            data: []
        }]
    },
    options: {
        scales: {
            xAxes: [{
                type: 'realtime'
            }]
        },
        plugins: {
            streaming: {
                onRefresh: function(chart) {
                    chart.data.labels.push(Date.now());
                    chart.data.datasets[0].data.push(
                        Math.floor(10 + Math.random() * 80)
                    );
                },
                delay: 2000
            }
        }
    }
});

Answer №2

Make sure to utilize version 2.5.0 of chartsjs

See it in action here : http://jsfiddle.net/kLg5ntou/93

var data = {
labels: ["0", "1", "2", "3", "4", "5", "6"],
datasets: [
    {
        label: "My First dataset",
        fillColor: "rgba(95,186,88,0.7)",
        strokeColor: "rgba(95,186,88,1)",
        pointColor: "rgba(0,0,0,0)",
        pointStrokeColor: "rgba(0,0,0,0)",
        pointHighlightFill: "rgba(95,186,88,1)",
        pointHighlightStroke: "rgba(95,186,88,1)",
        data: [65, 59, 80, 81, 56, 55, 40]
    }
]
};

var ctx = document.getElementById("chart").getContext("2d");
var chart = new Chart(ctx, {type: 'line', data: data});

setInterval(function () {
 chart.config.data.labels.push(Math.floor(Date.now() / 1000));
 chart.config.data.datasets[0].data.push(Math.floor(10 + Math.random() * 80));
 // maintain only 10 records
 chart.config.data.labels.shift();
 chart.config.data.datasets[0].data.shift();

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

No matter what I attempt, my presentation refuses to align in the center

My slideshow, which is powered by jQuery/JS and involves absolute positioning for each image, is causing me trouble when trying to horizontally center it on the page. No matter what I do, I can't seem to get it right. The challenge is not only getting ...

A large canvas displaying a single optimized image

Hello, I have a large image on the canvas that measures around 10,000 pixels by 10,000 pixels. I am looking for zoom in/out functionality. Can you recommend what technology I should use? Should I consider splitting the image into smaller segments like Go ...

What is the best approach to creating DOM elements in AngularJS?

My controller contains data with various actions and different numbers of parameters: $scope.actions = [ {name : 'rotate', r : '30'}, {name : 'translate', x : '10', y : '10'}, {name : 'scale', ...

Leveraging Google Cloud Functions with Next.js (Client-Side Rendering)

Having trouble incorporating firebase cloud functions into my Next.js project, encountering an unfamiliar error. firebase-config.js const firebaseConfig = { apiKey: '~~~', authDomain: '~~', projectId: '~~~', storageBu ...

Directing traffic from one webpage to another without revealing the file path in the Routes.js configuration

Recently starting out in Reactjs and utilizing Material-UI. My inquiry is regarding transitioning between pages using a sidebar, where in Material-UI it's required to display the page in the sidebar which isn't what I desire. var dashRoutes = [ ...

Tips on how to customize/ng-class within a directive containing a template using replace: true functionality

To keep replace: true, how can ng-class be implemented on the directive below without causing conflicts with the template's ng-class? This currently results in an Angular error: Error: Syntax Error: Token '{' is an unexpected token at co ...

Is there a way to execute code right before the jQuery submit() function is run?

I'm currently facing an issue with executing codes before a validation function runs in my form. I have tried different methods including referring to How to order events bound with jQuery, but without success. This is the code snippet I am working w ...

How can I notify a particular user using Node.js?

This is the code I have for my server in the server.js file: var socket = require( 'socket.io' ); var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = sock ...

React.js: Endless rendering occurs when using setState as a callback function, even after props have been destructured

Issue I am facing a problem with my child component that receives button id-name configurations as props. It renders selectable HTML buttons based on these configurations and then returns the selected button's value (id) to the callback function with ...

Arrange the columns in the Table in both ascending and descending order

While working on my React and MUI Table project, I encountered an issue with implementing sorting functionality for each column in both ascending and descending order. Whenever I click on the header to sort a column, an error message saying "Data is not it ...

Align component within material-ui grid

Looking to center align the same cards but not just the grid component, I need the content itself to be equally distant from the borders and each other. I've searched and tried different solutions without luck. https://i.stack.imgur.com/aZj7H.png htt ...

Using a personalized function in JQuery

I need to execute a JavaScript function I created after a JQuery event has been triggered. The function in question is called scrambleDot, and I defined it previously like so:var scrambleDot = new function() { //my code }. Here's the attempted implem ...

Tips for allowing divs to be dragged and resized within table cells and rows

UPDATE I believe that utilizing Jquery is the most appropriate solution for resolving my issue with the demo. Your assistance in making it work would be greatly appreciated. Thank you. My goal is to develop a scheduler application. https://i.sstatic.net ...

Issue with JQuery form submission causing controller method not to be executed

I am facing an issue with two click methods in my JavaScript code. Method 1 is successfully hitting the controller method, but when I try to trigger Method 2 by clicking on a button, it does not seem to call the controller. I have tried various solutions ...

"Exploring the capabilities of Rxjs ReplaySubject and its usage with the

Is it possible to utilize the pairwise() method with a ReplaySubject instead of a BehaviorSubject when working with the first emitted value? Typically, with a BehaviorSubject, I can set the initial value in the constructor allowing pairwise() to function ...

Creating a paragraph from text inputs using React

I'm currently working on code that retrieves input from two textboxes - one for a string value and one for a number value. I want this data to be displayed in real-time within a paragraph without the need for a submit button. I've been struggling ...

The `XMLHttpRequest.prototype.open` function does not capture every single HTTP request visible in the chrome-dev-tools

While utilizing a third-party embedded code that initiates HTTP requests with a request header origin different from my own, I encountered an issue. Despite attempting to intercept these HTTP requests using XMLHttpRequest, they do not get intercepted. This ...

Guide on how to showcase an array in a string format using table rows in JavaScript or jQuery

After making an AJAX call to a PHP database, I receive a String as a result in my script. The format of the string is shown below: array(4) { [0]=> array(3) { ["id"]=> string(3) "181" ["number"]=> ...

Incorporating HTML elements into a Jade template

Can HTML elements be passed into a jade file? For example, I want to insert text into the p element and nest some content inside the code element within the p element. JSON with string data var news = { one : { title : "Using JSON", body : "Us ...

The getElementByID function will return null in this instance, as it has not been loaded

Hello everyone, I am facing an issue while trying to access an element by its ID in JavaScript as it keeps returning null. This problem arises because the element is not fully loaded when the DOM is initially created, due to a plugin called Restrict Conte ...