Search code examples
pythonlinear-regressionaltair

How to change decimal format inside a transform_calculate function (Altair)


I'm trying to limit the numbers after the decimal in the text displayed in my graph, but I'm having a hard time doing so inside a transform_calculate function, this is what it looks like : (I am printing the equation to a linear regression under the form y = ax + b))

    params = alt.Chart(df).transform_regression(
        axe_x ,axe_y, params=True
    ).transform_calculate(
        intercept='datum.coef[0]',
        slope='datum.coef[1]'
    ).transform_calculate(
      text= "y = " + alt.datum.intercept + "x + " + alt.datum.slope

    ).mark_text(
        baseline="top",
        align="left"
    ).encode(
        x=alt.value(20),  # pixels from left
        y=alt.value(20),  # pixels from top
        text='text:N',
  )

I've tried many things like

      text= "y = " + f'format(datum.{intercept},".2f")' + "x + " + alt.datum.slope

and

      text= "y = " + alt.Text("alt.datum.intercept", format=".2f)  + "x + " + alt.datum.slope

Current output :

enter image description here

I'm a bit stuck here, help much appreciated thank you


Solution

  • You can use the Vega expression function round to round a value to the nearest integer:

    import altair as alt
    import pandas as pd
    import numpy as np
    
    np.random.seed(42)
    x = np.linspace(0, 10)
    y = x - 5 + np.random.randn(len(x))
    
    df = pd.DataFrame({'x': x, 'y': y})
    
    chart = alt.Chart(df).mark_point().encode(
        x='x',
        y='y'
    )
    line = chart.transform_regression('x', 'y').mark_line()
    
    params = alt.Chart(df).transform_regression(
        'x', 'y', params=True
    ).transform_calculate(
        intercept='round(datum.coef[0] * 100) / 100',
        slope='round(datum.coef[1] * 100) / 100',
        text= '["y = " + datum.intercept, "x + " + datum.slope]'
    ).mark_text(align='left').encode(
        x=alt.value(20),  # pixels from left
        y=alt.value(20),  # pixels from top
        text='text:N'
    )
    
    chart + line + params
    

    enter image description here