vega.lite axis and tooltip values: how to format number?

Hi,
I have a chart in which I have number like 60000000 (60 million).

Ho to format it in Italian way, comma as decimal separator and dot as thousands separator?
To have it in this way 60.000.000,00.

Thank you

vl
  .markBar()
  .data(totaleProvince)
  .encode(
    vl.tooltip([{ field: "totale", title: "Totale" }]),
    vl.y().fieldN("Provincia"),
    vl
      .x()
      .fieldQ("totale")
      .axis({ title: "Totale contributi in €", format: ".0f" })
  )
  .render()
1 Like

You need to add a custom formatType function to do the formatting.

totalePerProvince = vl
  .markBar()
  .data(totaleProvince)
  .encode(
    vl.tooltip([{ field: "totale", title: "Totale", format: ".2f", formatType: 'iformat'  }]),
    vl.y().fieldN("Provincia"),
    vl.x()
      .fieldQ("totale")
      .axis({ title: "Totale contributi in €", format: ".0f"   })
  )
  .width(width)
  .autosize("fit")
  .render()

to make the function you add this cell

vl.vega.expressionFunction('iformat',(datum, params) => {
  return   ilformat(datum);
});

That cell calls this to uses d3.formatLocal to define the formatting

ilformat = ilocale.format("$,")

which references this.

ilocale = d3.formatLocale({
  decimal: ",",
  thousands: ".",
  grouping: [3],
  currency: ["", "\u00a0€"],
  minus: "\u2212",
  percent: "\u202f%"
})

From that you should be able to work out how to add the iformat to the axis too.

1 Like

You are very kind, thank you. It works for the tooltip, but not for the axis, the thousands separator is always the , and not the ..
What’s wrong in my code?

That looks like a bug as that should work. There is a work around using this bit of hackery.


        labelExpr: "replace(toString(format(datum.value,',.0f')),/,/g,'.')",
        // format: ",.0f",
        // formatType: "iformat"

It uses an expression to construct the axis label by first formatting the datum then converting it to a string and then uses a regex to replace the ,'s with .'s

The regex is /,/g which makes the line confusing as the comma is not a parameter separator in the replace expression.

1 Like

Thank you again, it works!

In my opinion, this all works, but it seems to me very complex.

1 Like

It is a bit, people seem to have pivoted to using observable plot which is less complex.

I don’t know VL at all really, so it was an interesting challenge to debug :smiley:

1 Like