Altair - 在图中画一条线,其中 x = y

Altair - draw a line in plot where x = y

这段代码:

chart = alt.Chart(df).mark_point(filled=True).encode(
      alt.X('Goals Conceded:Q'),
      alt.Y('Goals:Q'),
      alt.Size('Goals:Q', legend=None, scale=alt.Scale(range=[0, 1500])),
      alt.Color('Color', legend=None, scale=None),
      tooltip = [alt.Tooltip('For Team:N'),
                alt.Tooltip('Goals:Q'),
                alt.Tooltip('Goals Conceded:Q')]
      ).properties(
          width=800,
          height=600
      )

地块:

现在我想手动添加一行,其中 x = y,以获得以下结果:


我该怎么做?

您可以添加一个虚拟行:

line = pd.DataFrame({
    'Goals Conceded': [0, 2],
    'Goals': [0, 2],
})

line_plot = alt.Chart(line).mark_line(color= 'red').encode(
    x= 'Goals Conceded',
    y= 'Goals'.
)

chart + line_plot

我没有你的数据集,所以下面是一个主要借用自 Altair Example Gallery 的例子:

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

source = data.iris()

iris_plot = alt.Chart(source).mark_circle().encode(
    alt.X('sepalLength'),
    alt.Y('sepalWidth'),
    color='species',
    size='petalWidth'
)

line = pd.DataFrame({
    'sepalLength': [0, 5],
    'sepalWidth':  [0, 5],
})

line_plot = alt.Chart(line).mark_line(color= 'red').encode(
    x= 'sepalLength',
    y= 'sepalWidth',
)

iris_plot + line_plot