Search code examples
vega-litevega

How to combine text and a field value in a single line of display


I am using Vega and I am stuck on this simple issue. I want to display

The yield is 43.67%

However using the samples provided I have managed to just display the value 43.67

{
  mark:
    {
      type: "text",
      align: "center",
      fontSize: 40,
      fontWeight: "bold"
    },
  encoding: 
    {
      "text": {"field": "Yield", "type": "quantitative",format: ".2f"}
    }
}

Is it possible to add some text in front of this value and put a % sign after it?


Solution

  • THe best way to add this sort of complicated annotation is using a calculate transform; for example:

    {
      mark:
        {
          type: "text",
          align: "center",
          fontSize: 40,
          fontWeight: "bold"
        },
      transform:
        [
          {"calculate": "'The yield is ' + datum.Yield + '%'", "as": "annotated_yield"}
        ],
      encoding: 
        {
          "text": {"field": "annotated_yield", "type": "nominal"}
        }
    }