Iulia Mihet
Iulia Mihet

Reputation: 700

Custom label text in Vega chart

Very simple question: I have a Vega chart and for the x-axis, I want to show "low" and "high" instead of 0 and 1 (which are the min and max of the domain).

So my x scale looks like this:

{
   'name': 'xscale',
   'type': 'linear',
   'domain': [0, 1],
   'range': 'width',
   'round': true,
   'zero': true,
   'nice': true
 }

while my axis looks like this:

{
  'orient': 'bottom',
  'scale': 'xscale',
  'tickCount': 1,
  'title': 'Prices
}

I can see in the documentation that I can customize the labels text, but it's not clear to me how. Thanks!

Upvotes: 1

Views: 1561

Answers (1)

Iulia Mihet
Iulia Mihet

Reputation: 700

So basically the solution is very simple. I got some inspiration from this github post: https://github.com/vega/vega/issues/714

You just need to have a ternary expression that would return the result of the text of the labels. Of course, this only works for an axis with 2 values, min and max.

'encode': {
          'labels': {
            'update': {
              'fill': { 'value': '#FF0000' },
              'align': { 'value': 'left' },
              'baseline': { 'value': 'middle' },
              'dx': { 'value': 0 },
              'dy': { 'value': 12 },
              'text': { 'signal': 'datum.value === 1 ? "High" : "Low"' }
            }
          }
        }

That's it. Now, instead of 1, the label will read "High", and instead of 0, the label will read "Low".

Upvotes: 2

Related Questions