Search code examples
vega-litevega

Background bands and specific labels in Vega Lite


1 - Im attempting to create a chart which displays 4 sections based on values on each axis (-x,-y)(-x,y)(-y,x)(xy), is there a way to set a separate background colour for each section? 2 - is there a way to add a permanent label to specific data points (text function i believe)

enter image description here

Tried text function but not sure about background


Solution

  • enter image description here

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "config": {"background": "white", "view": {"stroke": "transparent"}},
      "data": {
        "url": "https://raw.githubusercontent.com/GeorgeRobbin/GeorgeRobbin.github.io/main/Chart2_HPI%3AMR.csv",
        "format": {"type": "csv"}
      },
      "encoding": {
        "x": {
          "field": "Mortgage Rate Annual % Change",
          "scale": {"zero": false},
          "type": "quantitative",
          "axis": {"grid": false},
          "title": "Mortgage Rate Annual % Change"
        },
        "y": {
          "field": "House Price Annual % Change",
          "scale": {"zero": false},
          "type": "quantitative",
          "axis": {"grid": false},
          "title": "House Price Annual % Change"
        },
        "tooltip": [{"field": "Date", "type": "temporal", "title": "Name"}]
      },
      "layer": [
        {
          "mark": {"type": "rect"},
          "data": {
            "values": [
              {"x": 0, "y": 0, "x2": -29.9, "y2": -15, "c": "#cfdaef"},
              {"x": -29.9, "y": 0, "x2": 0, "y2": 20, "c": "#ffe9b7"},
              {"x": 0, "y": 0, "x2": 90, "y2": -15, "c": "#dbebd2"},
              {"x": 0, "y": 0, "x2": 90, "y2": 20, "c": "#facfb7"}
            ]
          },
          "encoding": {
            "x": {"field": "x"},
            "y": {"field": "y"},
            "x2": {"field": "x2"},
            "y2": {"field": "y2"},
            "color": {"field": "c", "scale": null}
          }
        },
        {"mark": {"type": "circle", "color": "red", "opacity": 0.7}},
        {
          "mark": {"type": "text"},
          "transform": [
            {
              "filter": {
                "field": "Date",
                "oneOf": [
                  {"year": 2022, "month": "jan", "date": 4},
                  {"year": 2009, "month": "jan", "date": 3}
                ]
              }
            }
          ],
          "encoding": {"text": {"field": "Date", "type": "temporal"}}
        }
      ],
      "height": 300,
      "width": 500
    }