首页 > 解决方案 > 日期表达式轴的本地化

问题描述

我尝试在 altair 时间序列图上将时间轴显示为本地化月份。我将 localed 设置为适当的代码,但 october 仍然显示为 oct 而不是 Okt。

import altair as alt
import pandas as pd
import locale
from altair_saver import save

file = '.\lagebericht.csv'
df = pd.read_csv(file, sep=';')

source = df
locale.setlocale(locale.LC_ALL, "de_CH")

base = alt.Chart(source, title='Neumeldungen BS').encode(
    alt.X('test_datum:T', axis=alt.Axis(title="",format="%b %y"))
    )

bar = base.mark_bar(width = 1).encode(
    alt.Y('faelle_bs:Q', axis=alt.Axis(title="Anzahl Fälle"))
    )

line =  base.mark_line(color='blue').encode(
    y='faelle_Total:Q')

chart1 = (bar + line).properties(width=600)

base = alt.Chart(source, title='Meldungen kumulativ BS').encode(
    alt.X('test_datum:T', axis=alt.Axis(title="",format="%b %y"))
    )
line =  base.mark_line(color='blue').encode(
    alt.Y('faelle_bs_kum:Q', axis=alt.Axis(title="Anzahl Fälle"))
    )
            
chart2 = (line).properties(width=600)
save(chart1 & chart2, r"images\figs.html")

标签: pythonaltair

解决方案


Altair 将 Python 和 javascript 连接起来;当您使用 Pythonlocale包时,它只会影响 Python 中的语言环境。您需要做的是更改 javascript 显示的区域设置。您可以通过渲染器embedOptions使用formatLocale(参见https://github.com/d3/d3-format/tree/master/locale)和timeFormatLocale(参见https://github.com/d3/d3-time-format/tree /master/locale )

以下是如何使用这些链接中可用的语言环境设置为 Altair 渲染设置 DE 语言环境:

import altair as alt
from urllib import request
import json

# fetch & enable a German format & timeFormat locales.
with request.urlopen('https://raw.githubusercontent.com/d3/d3-format/master/locale/de-DE.json') as f:
  de_format = json.load(f)
with request.urlopen('https://raw.githubusercontent.com/d3/d3-time-format/master/locale/de-DE.json') as f:
  de_time_format = json.load(f)
alt.renderers.set_embed_options(formatLocale=de_format, timeFormatLocale=de_time_format)

推荐阅读