Altair:提取和显示回归系数

Altair: Extract and display regression coefficients

解决了如何使用 mark_text()

访问和显示 R2

我对访问和显示系数很感兴趣。将 rSquared 替换为 coef 会产生截距和斜率的扁平数组,如 documentation.

中所述

我怎样才能对该数组进行索引以仅显示其中一个值,例如斜率? 我想知道是否可以在 mark_text() 步骤之前使用 transform (possibly transform_filter(), or if altair.Text()

我知道 approaches 涉及单独确定此信息,然后将其添加为附加层。

如果这是一个非常简单的问题,我们深表歉意。提前致谢。

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
).mark_text(align='left').encode(
    x=alt.value(20),  # pixels from left
    y=alt.value(20),  # pixels from top
    text='rSquared:N',

    # text='coef:N' # flattened array
    # text='coef[0]:N' # fails
)

chart + line + params

您可以使用计算转换访问它:

params = alt.Chart(df).transform_regression(
    'x', 'y', params=True
).transform_calculate(
    intercept='datum.coef[0]',
    slope='datum.coef[1]',
).mark_text(align='left').encode(
    x=alt.value(20),  # pixels from left
    y=alt.value(20),  # pixels from top
    text='intercept:N'
)

chart + line + params