简体   繁体   中英

How to create new date from offset in Vega?

I want to create a new date field using a field containing seconds and a field using time.

I've tried adding an additional field {calculate: "toDate(datum._source['TimeStamp']-datum._source['Metric'])", as: "time2"}

I'd like to plot Y against time as blue points and Y against time2 as red points. When I include the time2 expression and plot against it the graph comes back empty without error. I know I need to do something involving converting either the Date or Metric that can be subtracted.

Ex: "TimeStamp": July 1st 2019, 09:16:44.000 "Metric": 0.3 <-seconds

  $schema: https://vega.github.io/schema/vega-lite/v2.json
  data: {
    url: {
      %context%: true
      %timefield%: TimeStamp
      index: a.index*
      body: {
        size: 10000
        _source: ["@timestamp", "TimeStamp", "Metric", "TxnType","Y"]
      }
    }
    format: {property: "hits.hits"}
  }
  transform: [
    {calculate: "toDate(datum._source['TimeStamp'])", as: "time"},
    {"filter": "datum._source['Y'] > 0"},
    {"filter": "datum._source['TxnType'] == 'Type'"}

  ]

  mark: circle
  encoding: {
    x: {field: "time", type: "temporal",
    }
    y: {field: "_source.Y", type: "quantitative", "scale": {"type": "log"}}
  }
}```

Starting with Vega 5.8 you can use the timeOffset() function in expressions.

From https://vega.github.io/vega/docs/expressions/#timeOffset

timeOffset(unit, date[, step]) ≥ 5.8
Returns a new Date instance that offsets the given date by the specified time unit in the local timezone. The optional step argument indicates the number of time unit steps to offset by (default 1).

Assuming your field TimeStamp is a timepoint from which the offset Metric (in seconds) should be subtracted, then you would use

"transform": [
  {
    "calculate": "timeOffset('seconds', datum.TimeStamp, -datum.Metric)",
    "as": "time"
  }
]

If that does not work, make sure that datum.TimeStamp is a date object. Eg by specifying

"data": {
  ...,
  "format": {"parse": {"TimeStamp": "date"}}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM