Search code examples
localealtair

Setting Altair FormatLocale isn't working


import altair as alt
import pandas as pd
from urllib import request
import json

# fetch & enable a Brazil format & timeFormat locales.
with request.urlopen('https://raw.githubusercontent.com/d3/d3-format/master/locale/pt-BR.json') as f:
  pt_format = json.load(f)
with request.urlopen('https://raw.githubusercontent.com/d3/d3-time-format/master/locale/pt-BR.json') as f:
  pt_time_format = json.load(f)
alt.renderers.set_embed_options(formatLocale=pt_format, timeFormatLocale=pt_time_format)

df = pd.DataFrame({
    'date': pd.date_range('2020-01-01', freq='M', periods=6),
    'revenue': [100000, 110000, 90000, 120000, 85000, 115000]
})

a = alt.Chart(df).mark_bar().encode(
    y='month(date):O',
    x=alt.X('revenue:Q', axis=alt.Axis(format='$,.0f'))
)

a.save('tst.html')

When I run the code I expect the revenue to be formatted using "R$" as prefix. But still getting "$". I checked pt_format and I could see "R$" for currency as below. {'decimal': ',', 'thousands': '.', 'grouping': [3], 'currency': ['R$', '']} It seems alt.renderers.set_embed_options is not working. I have no clue. Any help would be appreciated


Solution

  • alt.renderers settings only apply to charts being displayed by a renderer, e.g. in Jupyter Notebook: it does not affect charts being saved to HTML via chart.save().

    In this case you can pass the embed options directly to the save() command:

    chart.save('chart.html', embed_options=dict(formatLocale=pt_format, timeFormatLocale=pt_time_format))