Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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.

like image 410
synapski Avatar asked Feb 02 '26 11:02

synapski


1 Answers

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.

like image 135
floribon Avatar answered Feb 04 '26 03:02

floribon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!