首页 > 解决方案 > 设置 Altair FormatLocale 不起作用

问题描述

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')

当我运行代码时,我希望使用“R$”作为前缀来格式化收入。但仍然得到“$”。我检查了 pt_format,我可以看到货币的“R$”,如下所示。{'decimal': ',', 'thousands': '.', 'grouping': [3], 'currency': ['R$', '']} 似乎 alt.renderers.set_embed_options 不起作用。我没有线索。任何帮助,将不胜感激

标签: localealtair

解决方案


alt.renderers设置仅适用于由渲染器显示的图表,例如在 Jupyter Notebook 中:它不会影响通过chart.save().

在这种情况下,您可以将嵌入选项直接传递给save()命令:

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

推荐阅读