Search code examples
javascriptjquerycanvasjs

Draw grid lines using Canvas js logarithmic chart


i have created a chart using canvas js library but i am having issue while displaying grid lines on the chart

<!DOCTYPE HTML>
<html>
<head>
  <script type="text/javascript">
  window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
      title: {
        text: "Axis Y with interval 20"
      },
      axisY:{
        logarithmic : true,
        gridthickness : 1,
        minimum : 10,
        maximum : 101,
     },
      data: [
      {
        type: "line",
        dataPoints: [
        { x: 100, y: 71 },
        { x: 200, y: 55},
        { x: 300, y: 50 },
        { x: 400, y: 65 },
        { x: 500, y: 95 },
        { x: 600, y: 68 },
        { x: 700, y: 28 },
        { x: 800, y: 34 },
        { x: 900, y: 14}
        ]
      }
      ]
    });

    chart.render();
  }
  </script>
  <script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
  <div id="chartContainer" style="height: 300px; width: 100%;">
  </div>
</body>
</html>

this is how i wanted the grid to be

this is how it looks now

anyone know how to properly format the grid lines, i have alse added demo snipped of how my data will look like


Solution

  • Minor grids are not available as of now. However by adding stripLines you can achieve the same as shown below.

    var chart = new CanvasJS.Chart("chartContainer", {
      title: {
        text: "Axis Y with interval 10"
      },
      axisY: {
        logarithmic: true,
        gridThickness: 0,
        tickThickness: 0,
        labelFormatter: function(e) {
          return ""
        },
        minimum: 10,
        maximum: 101,
      },
      data: [{
        type: "line",
        dataPoints: [
        	{ x: 100, y: 71 },
          { x: 200, y: 55},
          { x: 300, y: 50 },
          { x: 400, y: 65 },
          { x: 500, y: 95 },
          { x: 600, y: 68 },
          { x: 700, y: 28 },
          { x: 800, y: 34 },
          { x: 900, y: 14}
        ]
      }]
    });
    
    chart.render();
    addStripLines(chart);
    
    function addStripLines(chart) {
      var stripLines = [];
    
      for (var i = chart.axisY[0].minimum; i < chart.axisY[0].maximum;
        (i += 10)) {
        chart.axisY[0].addTo("stripLines", {
          value: i,
          label: i,
          labelPlacement: "outside",
          labelBackgroundColor: "transparent",
          labelFontColor: "black",
          color: "black"
        });
      }
    }
    <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>