Troubleshooting: HighCharts xAxis not displaying dates correctly when using JSON data

/* Analyzing Historical Performance */
document.addEventListener('DOMContentLoaded', function() {

  const lineChartUrl = 'https://bfc-dashboard-api.herokuapp.com/line_chart';

  Highcharts.getJSON(lineChartUrl, function(data) {

    var seriesData = [];
    var dates = [];

    var options = {
      series: [{
        name: 'Fund',
        data: seriesData,
      }],
      xAxis: {},
      yAxis: {
        title: {
          text: 'Value',
          style: {
            fontWeight: 'bold'
          }
        },
        crosshair: true,
        labels: {
          style: {
            color: '#77e8e3'
          }
        },
        gridLineColor: '#777'
      }
    };


    for (var i = 0; i < data.length; i++) {
      date = new Date(data[i][0]);
      seriesData.push(
        data[i][1],
        date
      );
    };

    //options.xAxis.categories = dates;  

    console.log(options);

    Highcharts.stockChart('chart-one', options);


  });

});
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/data.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<script src="https://code.highcharts.com/stock/modules/accessibility.js"></script>

<div id="chart-one"></div>

The formatting of the data to display in Highcharts is causing difficulty. While the line chart shows the data points, the dates on the xAxis appear as Jan 1, 1970 in a long time stamp. See screenshot

Currently, I am fetching JSON data, converting the date string to a Data object, and pushing the values to a new array called "seriesData" used to populate the points on the chart.

My goal is to have the dates displayed in DD/MM/YYYY format corresponding to their respective data point on the chart. Any suggestions are welcome. Despite similar topics existing, finding a suitable solution to the issue remains challenging.

document.addEventListener('DOMContentLoaded', function () {
    
    const lineChartUrl = 'https://bfc-dashboard-api.herokuapp.com/line_chart';
    
    Highcharts.getJSON(lineChartUrl, function(data) {
        
        var seriesData = [];
        var dates = [];
        
        var options = {
            series: [{
                name: 'Fund',
                data: seriesData,
            }],
            xAxis: {
            },
            yAxis: {
                title: {
                    text: 'Value',
                    style: {
                        fontWeight: 'bold'
                    }
                },
                crosshair: true,
                labels: {
                    style: {
                        color: '#77e8e3'
                    }
                },
                gridLineColor: '#777'
            }
        };
        
        
        for (var i = 0; i < data.length; i++) {
            date = new Date( data[i][0] );
            seriesData.push(
                data[i][1],
                date
            );
        };
        
        //options.xAxis.categories = dates;  
        
        console.log(options);
        
        Highcharts.stockChart('chart-one', options);

        
    });
    
});

Answer №1

The root cause of the issue lies in the format of the x value (date) provided by your JSON data. To resolve this, you can treat the date as a string in Highcharts by adjusting the xAxis.type to category.

Check out a live demo here: https://jsfiddle.net/BlackLabel/kgcvh4L7/

If you are working with Highstock, remember that the xAxis.type must be set to dateTime. In this case, make sure to convert your date data into a numeric form (such as a timestamp) before inputting it. By doing so, you will be able to customize the format of xAxis.labels accordingly:

Here is a snippet of the configuration code:

Highcharts.getJSON('https://bfc-dashboard-api.herokuapp.com/line_chart', function(json) {

  const data = [];

  json.forEach(point => {
    const myDate = point[0].split("/"),
      newDate = new Date(Date.UTC(myDate[2], myDate[0] - 1, myDate[1])).getTime();
    data.push([newDate, point[1]])
  })

  Highcharts.stockChart('container', {
    xAxis: {
      type: 'datetime',
      labels: {
        format: '{value:%d/%m/%Y}'
      }
    },

    series: [{
      data: data
    }]
  })

});

View another demonstration here: https://jsfiddle.net/BlackLabel/bvk45tsg/

For more information, refer to the API Reference: https://api.highcharts.com/highstock/xAxis.labels.format

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

The hyperlink does not appear to be functioning properly within a specific Div on the iPad. Interestingly, this issue does not persist when using other

Apologies if I am posting this question in the wrong place. I have a webpage (built with asp.net/vb) where each section is contained in divs within a Bootstrap grid. Through the code behind, I am attaching onclick events to each set of divs to perform sp ...

I am experiencing an issue where components are constantly re-rendering whenever I type something. However, I would like them to

Currently, I am in the process of developing a REACT application that takes two names, calculates a percentage and then generates a poem based on that percentage. The issue I am facing is that whenever I start typing in the input fields, the LovePercentCon ...

Mastering jQuery: Delegating a Toggle操作

Is there a way to implement a toggle function for an element that is generated dynamically? I am having trouble with my current code: Javascript $("body").on('click', ".buttonA", function(){ function() { ...

Is it possible to modify an HTML element when hovering over it in an ASP.Net page?

Is there a way to use jQuery to show the child span text - SomeClassChild3 string when hovering over the parent div - SomeClassParent in an aspx page? Here is the JavaScript section of the code: function ShowDiv(Somedata){ for(var v in Somedata){ va ...

Sending JSON data through the command line

When passing the following JSON via a command prompt: $python new.py {'scenarioId':'null','scenarioName':'EC_02','scenarioDesc':'EC_02','riskEngine':'null'} and running the c ...

Exploring the possibilities of utilizing React Router DOM with custom layouts

I am currently using layouts with react-router-dom in the following way: const DefaultLayout = ({children, ...rest}) => { return ( <div className={styles.wrapper}> <Header/> {children} <Foo ...

The GetJSON function is designed to fetch the entire array of data, without selectively retrieving specific

Below is the implementation of my GetJSON method: $(document).ready(function () { $.getJSON("/user", function (obj) { $.each(obj, function (key, value) { $("#usernames").append(value.firstname); console.log(ob ...

A straightforward method of transmitting data from JavaScript to the Python back-end within a Streamlit application

Utilizing the st.components.v1.iframe, I integrated an authentication system that sends a token back to the parent when a user is authenticated. The iframe content is as follows: <script src="remote/auth.js"></script> <scri ...

Can I send a JavaScript class to PHP as JSON in a different way?

As a beginner in this field, I am quickly learning and would greatly appreciate any kind of assistance. For example, I have an object like the following: function shape(name, size) { this.name = name; this.size = size; // additional function ...

Using Ramda, learn how to transform a flat list into a hierarchical one

Looking to transform the given list into a hierarchical structure with nested children fields. The 'parentId' attribute has been omitted for clarity, as it will be used in the transformation process using Ramda's immutable behavior. const x ...

What is the best way to showcase database values in a text-box using retrieval methods?

I am currently working on a database project that involves a webpage with 5 textboxes. One of these textboxes needs to display values from the database when it is in focus. I have the JavaScript and AJAX code to retrieve the data, but I am facing difficult ...

Using Vue to dynamically bind properties to newly created DOM elements

Imagine this scenario: I have a component with the template below: <div id="root"></div> Now, let's say that I execute some code that adds a new element to it (using jQuery at the moment): $('#root').append('<div id="a ...

Developing a division with an image source based on the selection of a checkbox

My goal is to develop a "change function" that generates a new div for each checked checkbox selection and removes the div when the checkbox is unchecked. These new divs should also display the img src of the selected checkbox. Currently, my JavaScript c ...

When my route in NextJS processes the request, it returns a ReadableStream from req

I am encountering an issue with my code and I have tried looking for solutions in other similar questions without any success. Is there anyone who can assist me? Here is the content of my route.js file: import dbConnect from "@/lib/dbConnect"; i ...

Convert XML to JSON with Azure

Seeking assistance with transforming XML to JSON using Azure liquid mapping in order to extract the session ID. <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3. ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

Having trouble figuring out what is causing non-serializable error in Redux (Redux error)

Initially, my react-native application was functioning smoothly and this particular page (screen) had been developed and working perfectly. However, out of the blue, it has started to encounter an error related to non-serializable data in the 'save_re ...

What is the best way to postpone the loading of an image and show a loading.gif for a few seconds before it appears on the screen? (with the help of jQuery or JavaScript)

My dilemma involves two images: -loading.gif (a loading animation) -scenery.jpeg (the image I want to display after the loading process); Since scenery.jpeg is a small file, using the load() function will simply skip over loading.gif So, when I click t ...

The error message in Express points to module.js line 550 and states that the module cannot be

I am currently in the process of setting up a basic express application using the code below: const express = require('express'); const app = express() const bodyParser = require('body-parser'); const cookieParser = require('cooki ...

Request Pending | Observation of WebSockets in NestJS

I'm currently working on a NestJS application that interacts with the Binance Websocket API to retrieve some data. While I am able to see all the data in my console.log, I'm facing an issue where the request seems to be pending when using Postman ...