Al R.
Al R.

Reputation: 2480

How do I format text marks as a percentage in vega.js?

Just starting out with Vega and am working through some simple examples. One basic thing I'm having a hard time with is labeling bar values in a bar chart. I can get the text mark to display properly, but can't figure out how to format the data value as a percentage ('.0%'). I've tried with string templates but haven't had any luck.

Here's the relevant snippet from my vega specification:

    {
      "type": "text",
      "from": {"data":"table"},
      "encode": {
        "enter": {
          "align": {"value": "center"},
          "baseline": {"value": "bottom"},
          "fill": {"value": "#333"}
        },
        "update": {
          "x": {"scale": "xscale", "field": "category", "band": 0.5},
          "y": {"scale": "yscale", "field": "amount", "offset": -2},
          "text": {"field":"amount", "template":"{{datum.amount|number:'.0%'}}" },
          "fillOpacity": {"value":1}
        }
      }
    }

Here's a link to my toy example

Upvotes: 3

Views: 2700

Answers (1)

Al R.
Al R.

Reputation: 2480

For others seeing this, here's the solution I arrived at

Things I had to figure out:

  1. The string template syntax is deprecated
  2. Add formatted values to the input data as a transform see here for expression syntax
  3. You can reference the bars as a data source and pull in computed x, y values (use the Vega Editor's handy "Data Viewer" to quickly inspect the data)
  4. To center the label over the bar use the "dx" attribute, setting it to half of the scale's band width: "dx": {"scale": "xscale", "band":0.5}

It was also helpful to review how vega derives values as I struggled with how to reference values from my data: https://vega.github.io/vega/docs/marks/#value-references. Again, using the Vega Editor's "Data Viewer" was super helpful.

Upvotes: 4

Related Questions