Joshua Ohana
Joshua Ohana

Reputation: 6141

Highcharts show x-axis with dates

I have a Highchart with x-axis at dates and fixed positions that I want to display as "Mar 2018"

It's defined as

xAxis: {
  type: "datetime",
  tickPositions: [
    new Date('2018-03-01'),
    new Date('2019-03-01'),
    new Date('2020-03-01'),
    new Date('2021-03-01'),
  ]
}

and series data as

data: [
  { x: new Date('2018-03-01'), y: 2.2 },
  { x: new Date('2019-03-01'), y: 3.3 },
  { x: new Date('2020-03-01'), y: 3.2 },
  { x: new Date('2021-03-01'), y: 3.8 },
]

With this setup no labels show up on the x-axis. I want there to be four ticks showing:

Mar 2018 - Mar 2019 - Mar 2020 - Mar 2021

I've tried using Date.UTC which has no change in tickPositions, and on series data it doesn't plot anything

I also tried using dateTimeLabelFormats dateTimeLabelFormats: { day: '%b %Y' } and label date formatter, both to no avail

labels: {
  formatter: function () {
    return Highcharts.dateFormat('%b %Y', this.value);
  }
}

chart

How can I get x-axis date labels to display?

Upvotes: 0

Views: 518

Answers (1)

madepiet
madepiet

Reputation: 884

Numbers are needed in tickPositions and new Date ('string') does not return it: https://jsfiddle.net/BlackLabel/e2gjqoty/

Also Date.UTC is slow so the months start indexing at 0: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC

  xAxis: {
    type: "datetime",
    tickPositions: [
      Date.UTC(2018,02,01),
      Date.UTC(2019,02,01),
      Date.UTC(2020,02,01),
      Date.UTC(2021,02,01)
    ]
  }

Upvotes: 1

Related Questions