synapski
synapski

Reputation: 333

'time' scale type in vega not working for javascript Date

Using the vega charting library, I'm dynamically loading my data from a javascript object. Values from that object contain a javascript date and an amount, for example :

[
  {date: new Date(2000, 0, 1), amount: 3}, 
  {date: new Date(2001, 0, 1), amount: 7}, 
  {date: new Date(2002, 0, 1), amount: 5}
]

A scale type of ordinal works fine but the scale type time gives me the following error :

Uncaught TypeError: ((intermediate value)(intermediate value) , group.scale(...)).rangeBand is not a function

How should I format my dates? (I tried to change the format.parse in the chart specification but it's not changing anything (I'm not parsing the data but directly loading it from a javascript object)).

The end goal is to display a subset of the dates on the x axis to avoid overlapping.

Upvotes: 3

Views: 666

Answers (1)

floribon
floribon

Reputation: 19183

The time scales in vega work on epoch timestamps, which are integers and not Dates.

It's very easy to obtain them from a JavaScript Date instance, simply apply getTime() (or valueOf()) on them

[
  {date: new Date(2000, 0, 1).getTime(), amount: 3}, 
  {date: new Date(2001, 0, 1).getTime(), amount: 7}, 
  {date: new Date(2002, 0, 1).getTime(), amount: 5}
]

I would like to add that the strength and nature of Vega specifications are to be serializable, i.e. you can write them as a string (or a JSON more precisely). Hence a Date instance wouldn't make sense as it is a complex prototype, so you can think these timestamps as serializations of Dates.

Upvotes: 1

Related Questions