我已成功在 Altair 中创建并渲染带有货币前缀 ($) 的图表,但我需要将其设置为 GBP (\xc2\xa3)。我知道有一个formatLocale可以设置的 Vega-lite,但我不知道如何将我需要的值传递给 Vega-lite。我在 Altair 文档中找不到有关区域设置的任何内容。
def chart_tenders_monthly_value(dataframe=None):\n chart = (\n alt.Chart(dataframe, title="Tender value")\n .mark_bar()\n .encode(\n alt.X(\n "yearmonth(date):O",\n axis=alt.Axis(title="Month") \n ),\n alt.Y("total_monthly_value:Q",\n axis=alt.Axis(title="Monthly cumulative tender value (\xc2\xa3)") \n ),\n tooltip=[\n alt.Tooltip(\'total_monthly_value:Q\', title="Total value", format="$,.4r"), \n alt.Tooltip(\'median_monthly_value:Q\', title="Median value", format="$,.4r"),\n alt.Tooltip(\'no_of_tenders:Q\', title="Total tenders", format=",.2r")\n ],\n color = \'variable:N\'\n )\n )\n\n text = (\n chart.mark_text(align="center", baseline="bottom")\n .encode(text=\'label:N\')\n .transform_calculate(label=f\'format(datum.total_monthly_value,"$,.3s")\')\n )\n return chart+text\nRun Code Online (Sandbox Code Playgroud)\n\n\n
在 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'))
)
Run Code Online (Sandbox Code Playgroud)
原答案:
这是可能的,但不幸的是没有得到很好的支持。formatLocale()是一个必须由渲染器调用的 JavaScript 函数。Jupyter Notebook 和 JupyterLab 使用的 Javascript 代码是硬编码在各自的 vega 扩展中的,因此无法为这些前端中可视化的 Altair 图表更改这一点。
如果您想自己调整区域设置,最简单的方法是将图表导出为 HTML ( chart.save('mychart.html')),然后添加调用formatLocale ),然后在 HTML 输出中的 javascript 中
如果您想以更自动/可重复的方式执行此操作,您可以修改 Altair 的 html 输出模板 ( source ) 并创建您自己的导出器函数,该函数使用区域设置或其他自定义 javascript 将图表转换为 HTML。
| 归档时间: |
|
| 查看次数: |
1041 次 |
| 最近记录: |