1

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=alt.value(20), text=alt.Text('rSquared:N', format='.4f'))

But I want to prepend "rSquared = " to the final text.

I've seen this answer involving an f string and a value calculated outside the chart, but I'm not clever enough to figure out how to apply that solution to this scenario.

I've tried, e.g., format='rSquared = .4f', but adding any additional text breaks the output, which I'm sure is the system working as intended.

Hadron Tungsten
  • 157
  • 1
  • 11

1 Answers1

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.git

import 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

eitanlees
  • 1,244
  • 10
  • 14