python - 如何在 Altair 中设置语言环境?

标签 python altair

我在 Altair 中成功创建并渲染了一个带有货币前缀 ($) 的图表,但我需要将其设置为 GBP (£)。我知道有一个 Vega-lite formatLocale 可以设置,但我不知道如何将我需要的值传递给 Vega-lite。我在 Altair 文档中找不到有关语言环境的任何内容。

   def chart_tenders_monthly_value(dataframe=None):
        chart = (
            alt.Chart(dataframe, title="Tender value")
                .mark_bar()
                .encode(
                alt.X(
                    "yearmonth(date):O",
                     axis=alt.Axis(title="Month") 
                     ),
                alt.Y("total_monthly_value:Q",
                     axis=alt.Axis(title="Monthly cumulative tender value (£)") 
                     ),
                tooltip=[
                    alt.Tooltip('total_monthly_value:Q', title="Total value", format="$,.4r"), 
                    alt.Tooltip('median_monthly_value:Q', title="Median value", format="$,.4r"),
                    alt.Tooltip('no_of_tenders:Q', title="Total tenders", format=",.2r")
                ],
                color = 'variable:N'
            )
        )

        text = (
            chart.mark_text(align="center", baseline="bottom")
            .encode(text='label:N')
            .transform_calculate(label=f'format(datum.total_monthly_value,"$,.3s")')
        )
        return chart+text

screenshot of rendered chart

最佳答案

在 Altair 4.0 或更新版本中,您可以通过渲染器嵌入选项设置格式区域设置和时间格式区域设置。语言环境是通过 JSON 对象设置的,这些对象紧凑地指定了值的显示方式。

  • formatLocale 选项,定义货币和数字的格式,可以在这里找到:https://github.com/d3/d3-format/tree/main/locale
  • timeFormatLocale 选项定义了时间和日期的格式,可以在这里找到:https://github.com/d3/d3-time-format/tree/main/locale

  • 以下是将渲染器设置为使用德语 (DE) 时间和货币格式的示例:
    import altair as alt
    import pandas as pd
    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)
    
    df = pd.DataFrame({
        'date': pd.date_range('2020-01-01', freq='M', periods=6),
        'revenue': [100000, 110000, 90000, 120000, 85000, 115000]
    })
    
    alt.Chart(df).mark_bar().encode(
        y='month(date):O',
        x=alt.X('revenue:Q', axis=alt.Axis(format='$,r'))
    )
    
    enter image description here

    原答案:
    这是可能的,但不幸的是没有得到很好的支持。 formatLocale() 是一个必须由渲染器调用的 javascript 函数。 Jupyter Notebook 和 JupyterLab 使用的 Javascript 代码在它们各自的 vega 扩展中进行了硬编码,因此对于在这些前端可视化的 Altair 图表,无法更改此代码。
    如果您想自己调整语言环境,最简单的方法是将图表导出为 HTML ( chart.save('mychart.html') ),然后在 HTML 输出的 javascript 中添加对 formatLocale 的调用。
    如果您想以更自动/可重复的方式执行此操作,您可以修改 Altair 的 html 输出模板 (source) 并创建您自己的导出器函数,该函数使用区域设置或其他自定义 javascript 将图表转换为 HTML。

    关于python - 如何在 Altair 中设置语言环境?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58014796/

    相关文章:

    python - 使用 python 客户端从 VM 创建镜像

    python - 功能无法正常使用(OpenCV Python)

    python - 向 Altair 图形添加背景实体填充

    python - 如何移除如图所示的 Altair yaxis?

    file - 有没有办法通过 postman 将文件上传到 GraphQL API?

    python-3.x - Altair 为交互式散点图 jar 添加日期 slider

    Python 按钮图像边框

    python - LPTHW :Ex48 Unit test(using nosetests), 类、方法参数类型错误

    python - 有没有办法可视化 3D 笛卡尔空间的方位角平均值?

    python - 如何使 Altair 分面图中的区域着色保持一致?