如何在Vega Lite图表中添加具有恒定值的垂直规则?

时间:2020-05-23 19:16:07

标签: vega-lite

我想向我的图表添加垂直的规则线作为日期里程碑指示符(如图像中的红线)。 X轴是日期(时间),y轴值是数字。

Vertical rule is the red line

在图像中,我可以使用规则层中数据属性的显式值获得的最接近的图像:

{
    "mark": "rule",
    "data": {
        "values": [
            "{\"x\":\"2020/04/10\"}"
        ]
    },
    "encoding": {
        "x": {
            "field": "x",
            "type": "ordinal",
        },
        "color": {
            "value": "red"
        },
        "size": {
            "value": 1
        }
    }
}

我也尝试过"type": "temportal""type": "quantitative", "aggregate": "distinct"这两种类型,但是没有运气。

我的目标是能够向图表中添加多个具有明确/恒定x值的红色垂直规则线。

1 个答案:

答案 0 :(得分:1)

Datum用于指定文字固定值。您可以通过将几个规则与主数据一起分层来添加多个规则。这种方法适用于x通道中编码的定量数据:

"layer": [
  {
    "mark": { "type": "line" },
    "encoding": { "y": {...}, },
  },
  {
    "mark": { "type": "rule", "color": "red", "size": 1, },
    "encoding": {"x": {"datum": 42}},
  },
  {
    "mark": { "type": "rule", "color": "blue", "size": 1, },
    "encoding": {"x": {"datum": 100}},
  },
]

要处理时间数据,您还必须指定如何解析时间数据。这种方法对我有用:

"layer": [
  {
    // First layer: spec of your main linear plot.
  },
  {
    // Second layer: spec of the vertical rulers.
    "mark": { "type": "rule", "color": "red", "size": 2, },
    "encoding": {
      "x": { "field": "date", "type": "temporal", },
    },
    "data": {
      "values": [
        {"date": "25 May 2020 14:15:00"},
        {"date": "25 May 2020 14:20:59"},
      ],
      "format": {
        "parse": {"date": "utc:'%d %b %Y %H:%M:%S'"}
      }
    },
  },
]