Nguyen Nhan
Nguyen Nhan

Reputation: 31

Chartjs: Draw chart with only yAxis zero tick

Hell, all,

I would like to draw the chart like this:

Chart example

Currently, I can use afterBuildTicks to get only zero yAxis. But the problem is that the whole other ticks were removed also. So Not sure if we have a way to draw zero tick and keep other ticks hidden except the label.

var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Value 1', 'Value 2', 'Value 3', 'Value 4'],
    datasets: [{
      label: "Dataset",
      data: [20, 15, 27, 18],
      backgroundColor: 'rgba(54, 162, 235,0.5)',
    }],
  },
  options: {
  responsive: true,
    elements: {
      line: {
        fill: false
      }
    },
  scales: {
    xAxes: [
      {
        position: 'top',
        display: true,
        gridLines: {
          display: true,
        },
        stacked: true,
        ticks: {
          fontColor: "#C4C4C4",
          fontSize: 10,
        }
      }
    ],
    yAxes: [
      {
        type: 'linear',
        display: true,
        position: 'right',
        id: 'y-axis-1',
        gridLines: {
          display: true,
        },
        labels: {
          show: true
        },
        stacked: false,
        ticks: {
          fontColor: "#C4C4C4",
          fontSize: 10,
          precision: 0,
          suggestedMax: 100,
          suggestedMin: -100
        },
        afterBuildTicks:function (axis) {
        axis.ticks = [0]
        }
      }
    ]
  },
  tooltips: {
    mode: 'label',
    bodySpacing: 10,
    titleMarginBottom: 10,
    titleFontSize: 14,
    titleFontStyle: 'bold',
    footerAlign: 'right',
    callbacks: {
      label: (tooltipItem, data) => {
        const label = data.datasets[tooltipItem.datasetIndex].label || ''
        const value = tooltipItem.value
        return `   ${label}: ${value}`
      }
    }
  }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>

Thanks so much

Upvotes: 2

Views: 253

Answers (1)

Nguyen Nhan
Nguyen Nhan

Reputation: 31

I found the solution that use: gridLines options to draw chart with width is zero:

gridLines: {
  display: true,
  tickMarkLength: 10,
  lineWidth: 0
}

Upvotes: 1

Related Questions