Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ChartJS bar not showing up for simple data points

Here's a simple chart.js horizontal bar chart I'm using:

var myBarChart = new Chart(ctx,{
  type: 'horizontalBar',
  data: {
    labels: [
        "Foo",
        "Bar",
        "Baz"
    ],
    datasets: [
    {
        data: [725000, 600000, 900000],
        backgroundColor: [
          "#ccf6ec",
          "#ff6654",
          "#009784"
        ],
        hoverBackgroundColor: [
          "#ccf6ec",
          "#ff6654",
          "#009784"
        ]
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        display: false
      }],
      yAxes: [{
        display: false
      }],
    }
  }
});

enter image description here


If I change the values to be closer to each other I see the three bars. I need it to draw the bars so they are always visible, even if the values are widely different.

Is there a configuration I missed? How can I fix this?

like image 930
Sergio Tapia Avatar asked Mar 03 '17 22:03

Sergio Tapia


People also ask

How do you make a bar graph on Chartjs?

Bar charts are created by setting type to bar (to flip the direction of the bars, set type to horizontalBar ). The colors of the bars are set by passing one color to backgroundColor (all bars will have the same color), or an array of colors.


1 Answers

For some reason, chart.js uses the smallest amount in data as minimum ticks value. Simply adding ticks.min: 0 apparently solves the issue:

var ctx = document.getElementById('chart')
var myBarChart = new Chart(ctx, {
  type: 'horizontalBar',
  data: {
    labels: [
      "Foo",
      "Bar",
      "Baz"
    ],
    datasets: [{
      data: [725000, 600000, 900000],
      backgroundColor: [
        "#ccf6ec",
        "#ff6654",
        "#009784"
      ],
      hoverBackgroundColor: [
        "#ccf6ec",
        "#ff6654",
        "#009784"
      ]
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        display: false,
        ticks: {
          min: 0
        }
      }],
      yAxes: [{
        display: false
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="chart" width="400" height="400"></canvas>
like image 78
Yohanes Gultom Avatar answered Sep 23 '22 03:09

Yohanes Gultom