Skip to content Skip to sidebar Skip to footer

How To Add Prefix To Rsquared Extracted From Altair?

I'm adding the rSquared to a chart using the method outlined in this answer: r2 = alt.Chart(df).transform_regression('x', 'y', params=True ).mark_text().encode(x=alt.value(20), y=a

Solution 1:

One possible solution using the posts you linked to would be to extract the value of the parameter using altair_transform and then add the value to the plot. This is not the most elegant solution but should achieve what you want.

# pip install git+https://github.com/altair-viz/altair-transform.gitimport altair as alt
import pandas as pd
import numpy as np
import altair_transform


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  = chart.transform_regression('x','y', params=True).mark_line()
R2 = altair_transform.extract_data(params)['rSquared'][0]


text = alt.Chart({'values':[{}]}).mark_text(
    align="left", baseline="top"
).encode(
    x=alt.value(5),  # pixels from left
    y=alt.value(5),  # pixels from top
    text=alt.value(f"rSquared = {R2:.4f}"),
)


chart + line + text

scatter plot with a regression line

Post a Comment for "How To Add Prefix To Rsquared Extracted From Altair?"