Search code examples
htmlchartshtml5-canvascanvasjs

How can I show only "Date and Time" in X-axis in area spine chart in canvasjs?


I need to show only “Date and Month” in x-axis in Area spine chart. Currently, it shows YYYYMMDD h:i:s but I need to show only DDMM in x-axis.

I need to show only “Date and Month” in x-axis in area spine chart. For e.g Currently, it shows values (2010-10-05, 2012-02-12) values in x-axis but I need to show it (like 5 October, 12 February).

I am using the below code in Area Spine Chart of canvasjs.

$( document ).ready(function () {
    var chart1 = new CanvasJS.Chart("chartContainer1",
    {
        animationEnabled: true,
        title:{
            text: "Voting Trends"
        },
        axisY: {
            title: "VOTES",
            gridThickness: 0
        },
        data: [{
            type: "splineArea",
            color: "rgba(54,158,173,.7)",
            markerSize: 5,
            xValueFormatString: "",
            dataPoints: [      
                {x: "10 Jul", y: 1, indexLabel: "1"},
                {x: "11 Jul", y: 2, indexLabel: "2"}, 
            ]
        }]
    }); 
    chart1.render();
});

This code is not generating any values in the x-axis. Hence the graph does not show exact points on it. I just need to show these values in x-axis as: 11 July, 12 July, 13 July, etc. Any help would be appreciate.


Solution

  • CanvasJS supports numeric and date-object in x-values and not string. Passing x-value as date-object and setting valueFormatString to "D MMMM" shows axis labels as 5 October, 12 February, etc.

    var chart = new CanvasJS.Chart("chartContainer", {
      animationEnabled: true,
      title:{
        text: "Voting Trends"
      },
      axisX: {
        valueFormatString: "D MMMM",
        interval: 1,
        intervalType: "day"
      },
      axisY: {
        title: "VOTES",
        gridThickness: 0
      },
      data: [{
        type: "splineArea",
        color: "rgba(54,158,173,.7)",
        markerSize: 5,
        dataPoints: [      
          {x: new Date("Jul 10 2019"), y: 1, indexLabel: "1"},
          {x: new Date("Jul 11 2019"), y: 2, indexLabel: "2"}, 
        ]
      }]
    });
    
    chart.render();
    <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
    <div id="chartContainer" style="height: 250px; width: 100%;"></div>