Tom Martens
Tom Martens

Reputation: 214

visualize the duration of events

I want to visualize durations of events as a bar, my input value is a decimal value where the integer part represents days and the decimal part a fraction of a day. I can convert the input value to any value needed. An event can span multiple days. The code below contains data for two events, the duration of event a is 36 hours and the duration of event b is 12 hours. Of course, it's possible that an event can be over after just some minutes or take 3hours 14minutes 24seconds. I want the x-axis have ticks every 30minutes, from the sample data I need 36 hours, an axis label can look like 0d 0:00.

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "height": "container",
  "width": "container",
  "data": {
    "values": [
      {
        "event": "a",
        "durationdecimal": 1.5
      },
      {
          "event": "b",
        "durationdecimal": 0.5
      }
    ]
  },
  "mark": {"type": "bar"},
  "encoding": {
    "x": {
      "field": "durationdecimal",
      "type": "temporal",
      "axis": {"grid": false},
      "timeUnit": "utchoursminutes"
    },
    "y": {"field": "event", "type": "nominal", "title": null}
  ,
  "tooltip": [{"field": "durationdecimal"}]
  }
}

I appreciate any help.

Upvotes: 1

Views: 406

Answers (1)

wahab memon
wahab memon

Reputation: 2416

I don't think your durationdecimal should be temporal as there is no date/month/year provided. I tried recreating your sample using quantitative type and have done conversions on labels using labelExpr and some expressions. It mostly covers all your mentioned requirements. The only remaining part seems to be of ticks for 30 mins.

Below is the config or refer editor:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "height": "container",
  "width": "container",
  "data": {
    "values": [
      {"event": "a", "durationdecimal": 1.5},
      {"event": "c", "durationdecimal": 2.1},
      {"event": "b", "durationdecimal": 0.5}
    ]
  },
  "mark": {"type": "bar"},
  "transform": [
    {
      "calculate": "split(toString(datum.durationdecimal),'.')[0] + 'd ' + (split(toString(datum.durationdecimal),'.')[1] ? floor(('0.'+split(toString(datum.durationdecimal),'.')[1])*24) + ':00': '0:00')",
      "as": "x_dateLabelTooltip"
    }
  ],
  "encoding": {
    "x": {
      "field": "durationdecimal",
      "type": "quantitative",
      "axis": {
        "grid": false,
        "labelExpr": "split(toString(datum.label),'.')[0] + 'd ' + (split(toString(datum.label),'.')[1] ? floor(('0.'+split(toString(datum.label),'.')[1])*24) + ':00': '0:00')"
      }
    },
    "y": {"field": "event", "type": "nominal", "title": null},
    "tooltip": [{"field": "x_dateLabelTooltip"}]
  }
}

Let me know if this works for you.

Upvotes: 1

Related Questions