ThomasG
ThomasG

Reputation: 113

ChartJS Bar Issue - Showing "zeros" and not center bars

Im having some trouble with ChartJs and hope you can help. I would like to create a Bar Chart where:

I have added the code example here at codepen: Link to ChartJs CodePen

var Canvas = document.getElementById("myChart");


var Data1 = {
  label: 'Project A',
  data: [10, 0, 10, 0 ,0 ,0 ,10],
  backgroundColor: 'rgba(0, 99, 132, 0.6)',
  borderWidth: 0,
  yAxisID: "y-axis"
};

var Data2 = {
  label: 'Project B',
  data: [0 , 5, 5, 0 ,0 ,0 ,10],
  backgroundColor: 'rgba(99, 132, 0, 0.6)',
  borderWidth: 0,
  yAxisID: "y-axis"
};

var MonthData = {
  labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"],
  datasets: [Data1, Data2]
};

var chartOptions = {
  scales: {
    xAxes: [{
      barPercentage: 1,
      categoryPercentage: 0.6
    }],
    yAxes: [{
      id: "y-axis"
    }]
  }
};

var barChart = new Chart(Canvas, {
  type: 'bar',
  data: MonthData,
  options: chartOptions
});

Another example, please see below. I have added a link to the source. If i could add data to a Bar Chart the same way it would be perfect.

enter image description here Link to source of picture

EDIT: Added a codepen for DX chart: DX Link

/Thomas

Upvotes: 0

Views: 1433

Answers (2)

Julian
Julian

Reputation: 1

Changing intersect to false for the tooltips should fix the problem. (Intersect: true only shows the tooltips if you're hovering over a datapoint, of which there are none if it's zero)

tooltips configuration can be found here: https://www.chartjs.org/docs/2.6.0/configuration/tooltip.html

var chartOptions = {
  scales: {
    xAxes: [{
      barPercentage: 1,
      categoryPercentage: 0.6
    }],
    yAxes: [{
      id: "y-axis"
    }]
  },
  tooltips: {
    intersect: false
  }
};

Upvotes: 0

Martin M.
Martin M.

Reputation: 451

ChartJS and the DevExtreme chart are 2 different things. If you want the functionality of dxChart in chartJs then you would have to write it yourself (if you don't have access to the source code to see how they did it).

Helping you with the first point is easy - simply unset the data you don't want. Check here. Don't forget to remove the label you don't want to show.

for (let i = 0; i <= Data1.data.length; i++){
  if (Data1.data[i] === 0 && Data2.data[i] === 0) {
    Data2.data.splice(i, 1);
    Data1.data.splice(i, 1);
    labels.splice(i, 1); // also remove the corresponding label
    i--; // important not to skip any records after removing
  }
}

However this sort of data manipulation I would recommend doing in the back end. Just don't set it before sending to the front end and you're done.

For your second point it looks like chartJs cannot help. There is a reason why dxChart is paid and chartJs is free. Learn to make compromises or become a JS ninja. Cheers

Upvotes: 1

Related Questions