Home > OS >  how to disable default label for a particular dataset chart js
how to disable default label for a particular dataset chart js

Time:06-30

 this.myBarChart = new Chart('myBarChart', {
  type: 'bar',
  data: {
    labels: ["Voice Control Mode", "Manual Mode", "Automatic Mode","Single Drive Mode","Dual Drive Mode"],
    datasets: [
      {
        type: 'bar',
        label: "Recordings",
        backgroundColor: "rgba(2,117,216,1)",
        borderColor: "rgba(2,117,216,1)",
        data: [this.data.voicecontrolmode, this.data.manualmode, this.data.automaticmode,this.data.singledrivemode,this.data.dualdrivemode],
        order:2
      },
      {
        type: 'line',
        data: [this.data.totalrecordings, this.data.totalrecordings, this.data.totalrecordings,this.data.totalrecordings,this.data.totalrecordings],
        label: 'Total Recordings',
        backgroundColor: "rgba(150,29,255,1)",
        borderColor: "rgba(150,29,255,1)",
        pointRadius:0,
        pointHoverRadius:0,
        order:1
      }
    ]
  },
  options: {
    // plugins:,
    scales: {
      xAxis: {
        ticks: {
          maxTicksLimit: 6
        }
      },
      yAxis: {
        ticks: {
          maxTicksLimit: 5
        }
      }
    }
  }
});

I want to remove labels: ["Voice Control Mode", "Manual Mode", "Automatic Mode","Single Drive Mode","Dual Drive Mode"] for only the line chart so that total recordings is just a straight line but when I hover over that it should just say- Total Recordings:95(example). For the bar chart the labels should still show up.enter image description here

CodePudding user response:

You can add a second x axis with offset and display set to false, then map your line to that x axis:

const options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: 'pink'
      },
      {
        label: '# of Points',
        type: 'line',
        data: [23, 23, 23, 23, 23, 23, ],
        borderColor: 'orange',
        xAxisID: 'x2'
      }
    ]
  },
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          title: (ttItems) => (ttItems[0].dataset.type === 'line' ? '' : ttItems[0].label)
        }
      }
    },
    scales: {
      x: {},
      x2: {
        display: false,
        offset: false
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
</body>

EDIT:
You can use a custom tooltip title callback for this, see updated live example above.

options: {
  plugins: {
    tooltip: {
      callbacks: {
        title: (ttItems) => (ttItems[0].dataset.type === 'line' ? '' : ttItems[0].label)
      }
    }
  },
}
  • Related