vega-litevega

Enable multi line / wrap of single legend label text in vega-lite


I am trying to ensure that the text of the legend label (the text is not from the core data set, but separately declared values) will line break / wrap and not be clipped if the text string is too long.

The input data for the values could exceed the labelLimit value, so want to make sure the chart accounts for longer strings.

In the example chart, you can see I have set the legend values are datum's - enabling me to set the text values.

Example Chart on Vega-lite

I know that vega-lite has support for certain properties when array values are set, these are treated as line breaks, but this doesnt appear to work for the datum values.

Ideally, in the example provided, you would see the legend text for the first item appear as follows:

Here is the value for dataset 1

its really long


Solution

  • I'm still not 100% clear about why but you can hack your requirement with a labelExpr. Obviously, you'd use better logic to split your string into however many lines you want by the right delimiter.

    enter image description here

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "height": 500,
      "width": 500,
      "config": {
        "legend": {"direction": "horizontal", "orient": "bottom", "labelLimit": 150}
      },
      "data": {
        "values": [
          {"date": "2019-01-01", "field1": 55.1, "field2": 58.2},
          {"date": "2020-02-30", "field1": 58.1, "field2": 60.2},
          {"date": "2021-03-30", "field1": 62.1, "field2": 65.2}
        ]
      },
      "encoding": {
        "x": {
          "field": "date",
          "type": "temporal",
          "title": null,
          "timeUnit": "yearmonth"
        },
        "y": {"field": "value", "type": "quantitative", "title": "Value"},
        "color": {"type": "nominal", "scale": {"range": ["orange", "red"]}}
      },
      "layer": [
        {
          "mark": "line",
          "encoding": {
            "y": {"field": "field2", "title": "title1"},
            "color": {
              "datum": "Here is the value for dataset 1 its really long",
              "legend": {
                "title": "",
                "labelExpr": "[slice(datum.label,0,15),slice(datum.label,15)]"
              }
            }
          }
        },
        {
          "mark": "line",
          "encoding": {
            "y": {"field": "field1", "title": "title2"},
            "color": {
              "datum": "Here is the value for dataset 2 its really long",
              "legend": {
                "title": "",
                "labelExpr": "[slice(datum.label,0,15),slice(datum.label,15)]"
              }
            }
          }
        }
      ]
    }