简体   繁体   中英

How to add vertical Rule with constant value to Vega Lite chart?

I want to add vertical Rule lines to my chart as date milestone indicators (like the red line in image). X axis is dates (temportal), and y axis values are numbers.

垂直规则是红线

In image is the closest I could get using explicit values for data property in Rule layer:

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

I have also tried types: "type": "temportal" , and "type": "quantitative", "aggregate": "distinct" with no luck.

My goal is to be able to add multiple red vertical Rule lines with explicit/constant x values to the chart.

Datum is meant for specifying literal fixed values. You can add several rules by layering them together with your main data. This approach works with quantitative data encoded in the x channel:

"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}},
  },
]

For dealing with temporal data, you additionally have to specify how it should be parsed. This approach works for me:

"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'"}
      }
    },
  },
]

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