score:3

Accepted answer

The problem is with parsing the date string. Chart js uses moment adapter for date strings and this type ("May 2016") of format might not be easily parsed in some browsers, to see what kind of formats you can use check https://momentjs.com/docs/#/parsing/string-formats/

The code below should work for the second set of data

window.addEventListener('load', setup);
var formatDate = (dateString) => {
  return moment(dateString, "MMM YYYY").toDate()
}

async function setup() {
  var ctx = document.getElementById('myChart').getContext('2d');
  var dollar = await getData();
  var myChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: dollar.years.map(year => formatDate(year)),
      datasets: [{
        label: 'Unemployment rate',
        data: dollar.vals,
        borderColor: 'rgb(153,222,101)',
        backgroundColor: 'rgb(153,222,101, 0.2)',
        pointRadius: 0,
        borderWidth: 6,
        pointHitRadius: 10,
      }]
    },

    options: {
      layout: {
        padding: {
          left: 0,
          right: 15,
          top: 0,
          bottom: 0
        }
      },
      responsive: true,
      title: {
        display: false
      },

      legend: {
        display: false
      },

      scales: {
        yAxes: [{
          ticks: {
            min: 3,
            max: 8,
            stepSize: 1
          }
        }],

        xAxes: [{
          type: "time",
          time: {
            unit: "year",
            tooltipFormat: "YYYY"
          },

          gridLines: {
            display: true,
            drawOnChartArea: false,
          },

          ticks: {
            display: true,
            maxTicksLimit: 5,
            maxRotation: 0,
            minRotation: 0,
            padding: 1
          },
        }],
      }
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

score:1

in my case it didn't like my date pipe approach:

const date = '12/12/2021'.replace('/','-')
this.chartLabels.push(date)

didn't work, but this did

const transDate = new Date(it.asOfDate)
this.chatLabels.push(this.datePipe.transform(transDate, 'MM-dd-yyyy'))

Related Query

More Query from same tag