简体   繁体   中英

Adding R-value (correlation) to scatter chart in Altair

So I am playing around with the Cars dataset and am looking to add the R-value to a scatter chart. So I can use this code to produce a scatter chart using transform_regression to add a regression line which is great.

from vega_datasets import data
import altair as alt
import pandas as pd
import numpy as np

cars = data.cars()
chart = alt.Chart(cars).mark_circle().encode(
        alt.X('Miles_per_Gallon', scale=alt.Scale(domain=(5,50))),
        y='Weight_in_lbs'
)

chart + chart.transform_regression('Miles_per_Gallon','Weight_in_lbs').mark_line()

Here is the chart

在此处输入图像描述

Then I am looking get the R-value. So can use pandas with this code as I am not sure how to get the R-value with Altair.

corl = cars[['Miles_per_Gallon','Weight_in_lbs']].corr().iloc[0,1]
corl

Now I was wondering how would I go about adding the R-value on the chart as a sort of label?

You can do this by adding a text layer:

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"r: {corl:.3f}"),
)

chart + text + chart.transform_regression('Miles_per_Gallon','Weight_in_lbs').mark_line()

在此处输入图像描述

In future versions of Altair, the empty data in the chart will no longer be required.

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