Chartjs-First and last bar is partially hidden on bar chart with x-axis type 'time'

1👍

Although I can’t tell you why it happens, it can be fixed by setting a min and max value for the x axis in fuelChart.options.scales.x

const fuelChart = new Chart("chart", {
  "type": "bar",
  "data": {
    "datasets": [{
        "label": "Price",
        "data": [{
            "x": 1230764400000,
            "y": 1.795
          },          
          {
            "x": 1235862000000,
            "y": 1.96
          },
          {
            "id": "1000782",
            "x": 1238536800000,
            "y": 2.051
          },
          {
            "x": 1249077600000,
            "y": 2.62
          },         
          {
            "x": 1254348000000,
            "y": 2.557
          },
          {
            "id": "1000921",
            "x": 1257030000000,
            "y": 2.648
          },        
          {
            "x": 1262300400000,
            "y": 2.714
          },
          {
            "id": "1000981",
            "x": 1264978800000,
            "y": 2.651
          },       
          {
            "x": 1270072800000,
            "y": 2.855
          },       
          {
            "x": 1275343200000,
            "y": 2.727
          },
          {
            "x": 1277935200000,
            "y": 2.727
          },        
          {
            "x": 1283292000000,
            "y": 2.703
          }
        ],
        "backgroundColor": "rgba(78,121,167,0.75)",
        "borderColor": "rgba(78,121,167,1)",
        "borderWidth": 1
      }   
    ]
  },
  "options": {
    "scales": {    
      "x": {
        "min": 1230764400000,
        "max": 1283303000000,
        "offset": true,
        "type": "time",
        "time": {
          "unit": "day",
          "displayFormats": {
            "day": "d MMM yyyy"            
          },
          "tooltipFormat": "d MMM yyyy"
        }
      }
    }
  }
});

function minMax(){
  fuelChart.options.scales.x.min = fuelChart.data.datasets[0].data[0].x-1000000000;
  fuelChart.options.scales.x.max = fuelChart.data.datasets[0].data[fuelChart.data.datasets[0].data.length-1].x+1000000000
  fuelChart.update()
}

function resetMinMax(){
  fuelChart.options.scales.x.min = fuelChart.data.datasets[0].data[0].x
  fuelChart.options.scales.x.max = fuelChart.data.datasets[0].data[fuelChart.data.datasets[0].data.length-1].x
  fuelChart.update()
    
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@^1"></script>
<canvas id="chart"></canvas>

<button onclick=minMax()>Edit Min & Max</button>
<button onclick=resetMinMax()> Reset Min & Max </bbtton>

Leave a comment