简体   繁体   中英

To show B(Billion) instead of G(Giga) in altair charts python

Looking to replace G(Giga) with B(Billion) in a python code using altair charts. I researched quite a lot on this but cannot find a way to override d3 format in python. Currently using the below code for the axis format:

line1=(alt.Chart(df_combined).mark_bar().encode(
     x=alt.X('Date:T', axis=alt.Axis(title=None, grid=False, format= '%b-%Y')),
     y = alt.Y(
         'Current Year:Q',
         axis= alt.Axis(
             title=None,
                titleAngle=0,
                titleY=-20,
                titleAlign="left",
                format='s',
                titleColor=COLORS_HEX['SMOKEY_BLUE']),
              ),
    color = alt.value(COLORS_HEX['SMOKEY_BLUE'])
).add_selection(sel_selection).transform_filter(sel_selection)
)

however, this produces the axis and tool tip with SI notification which shows 10^9 as G and not B(billion). Lot of topics on this related subject shows to achieve this in javascript by overriding the d3 format function but how do I override this function by calling it in python notebook. Would be very helpful to get some pointers on this topic.

Thank you.

I don't know of any way to create custom d3 formatters from Python within the standard Altair display mechanisms. You can always export your chart to JSON and then use vega-embed to manually display your chart with whatever Javascript extras you wish.

From the Python side, one way to accomplish roughly what you want is to use labelExpr to define a custom label expression. For example:

import pandas as pd
import altair as alt
df = pd.DataFrame({'x': [1E9, 2E9, 3E9]})
alt.Chart(df).mark_point().encode(
    alt.X('x', axis=alt.Axis(tickCount=5, labelExpr='datum.value / 1E9 + "B"'))
)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM