hanzgs
hanzgs

Reputation: 1616

How to Annotate a Line in line Chart in Vega-Lite?

How to annotate a line in line chart in vega-lite For the below code https://vega.github.io/editor/#/

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "layer": [
    {
      "data": {"url": "data/stocks.csv"},
      "mark": "line",
      "encoding": {
        "x": {"field": "date", "type": "temporal"},
        "y": {"field": "price", "type": "quantitative"},
        "color": {"field": "symbol", "type": "nominal"}
      }
    },
    {
      "data": {"values": [{}]},
      "mark": {"type": "rule", "strokeDash": [2, 2], "size": 2},
      "encoding": {"x": {"datum": {"year": 2006}}}
    }
  ]
}

We get plot enter image description here

If I want to annotate the line at a specific position like (2004,400)

enter image description here

I tried this, it is working, but I don't want to pass hardcoded values like "a": 2004, "b": 400,

   {
      "data": {
        "values": [
          {"a": 2004, "b": 400}
       ]
     },
      "mark": {"type": "text", "fontSize" : 16, "fontWeight":"bold", "align" : "left"},
      "encoding": {
        "text": {"value": "Optimum"},
        "x": {"field": "a", "type": "quantitative", "title":""},
        "y": {"field": "b", "type": "quantitative", "title":""}     
      }
    },

How to pass specific values from the data like average value of date (say:2004) and average value of price (say:400)?

or

just next to the line in the middle of y-axis

Upvotes: 1

Views: 1342

Answers (1)

hanzgs
hanzgs

Reputation: 1616

Transform and Aggregate Worked, I needed only for Y axis average position, so below code worked good. For another axis we can use same transform.

    {
      "mark": {"type": "text", "fontSize" : 16, "fontWeight":"bold", "align" : "left"},
      "transform": [
        {
          "aggregate": [{
           "op": "mean",
           "field": "price",
           "as": "mean_y_axis"
          }],
          "groupby": ["date"]
        }
      ],      
      "encoding": {
        "text": {"value": "Optimum"},
        "x": {"field": "date",
              "type": "quantitative"},
        "y": {"field": "mean_y_axis",
              "type": "quantitative"}     
      }
    }

Upvotes: 1

Related Questions