在Altair中向散点图添加R值(相关性) [英] Adding R-value (correlation) to scatter chart in Altair

查看:117
本文介绍了在Altair中向散点图添加R值(相关性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在研究Cars数据集,并希望将R值添加到散点图中.因此,我可以使用此代码使用 transform_regression 来添加散点图,以添加一个很棒的回归线.

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()

这是图表

然后我正在寻找R值.因此可以在此代码中使用熊猫,因为我不确定如何使用Altair获取R值.

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

现在我想知道如何在图表上添加R值作为标签?

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()

在以后的Altair版本中,将不再需要图表中的空白数据.

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

这篇关于在Altair中向散点图添加R值(相关性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆