skip to Main Content

I have created a single line stacked horizontal bar chart with ChartJS v4.4.4. Additionally, I disabled the legend display, made the point radius equal to 0. I also added negative padding for layout and disabled the display of the grid, border and ticks. In general, everything that is advised in such cases. But as a result, the diagram has extra paddings (marked red) at the top and bottom. How can they be removed?

let barChart = new Chart(document.getElementById("canvas"), {
  type: "bar",
  data: {
    labels: ["Bar"],
    datasets: [
      {
        label: "Account 1",
        backgroundColor: "#3e95cd",
        pointRadius: 0,
        data: [{ x: [0, 10], y: "Bar" }],
      },
      {
        label: "Account 2",
        backgroundColor: "#8e5ea2",
        pointRadius: 0,
        data: [{ x: [10, 15], y: "Bar" }],
      },
      {
        label: "Account 3",
        backgroundColor: "#3cba9f",
        pointRadius: 0,
        data: [{ x: [15, 20], y: "Bar" }],
      },
    ],
  },
  options: {
    indexAxis: "y",
    responsive: true,
    maintainAspectRatio: false,
    layout: {
      padding: {
        left: -8,
        bottom: -8,
      },
    },
    scales: {
      y: {
        beginAtZero: true,
        stacked: true,
        border: {
          display: false,
        },
        ticks: {
          display: false,
        },
        grid: {
          display: false,
        },
      },
      x: {
        border: {
          display: false,
        },
        ticks: {
          display: false,
        },
        grid: {
          display: false,
        },
      },
    },
    plugins: {
      legend: {
        display: false,
      },
      tooltip: {
        enabled: false,
      },
    },
  },
})
.chart {
  background: red;
}
<div class="chart">
  <canvas class="chart__canvas" id="canvas"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

2

Answers


  1. Chosen as BEST ANSWER

    I found another solution. You can specify the barThickness parameter for the canvas size.

    options: {
        ...,
        barThickness: 150,
    },
    

    You can also set this parameter for each dataset separately.


  2. Set both barPercentage and categoryPercentage in the option to 1 to make the bar fully occupied without padding/spacing.

    Reference: barPercentage vs categoryPercentage

    let barChart = new Chart(document.getElementById("canvas"), {
      type: "bar",
      data: ...,
      options: {
        ...,
        barPercentage: 1,
        categoryPercentage: 1,
      },
    });
    

    Demo @ StackBlitz

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search